Java 문자열에서 숫자 확인 및 추출
사용자가 String을 다음과 같은 형식으로 입력하는 프로그램을 쓰고 있습니다.
"What is the square of 10?"
- 문자열에 번호가 있는지 확인해야 합니다.
- 그리고 숫자만 추출합니다.
- 사용하는 경우
.contains("\\d+")
또는.contains("[0-9]+")
입력 내용에 관계없이 프로그램이 String에서 숫자를 찾을 수 없습니다..matches("\\d+")
숫자만 있을 때만 작동합니다.
검색 및 추출을 위한 솔루션으로 사용할 수 있는 것은 무엇입니까?
이거 먹어봐
str.matches(".*\\d.*");
입력 문자열에서 첫 번째 숫자를 추출하려면 다음을 수행합니다.
public static String extractNumber(final String str) {
if(str == null || str.isEmpty()) return "";
StringBuilder sb = new StringBuilder();
boolean found = false;
for(char c : str.toCharArray()){
if(Character.isDigit(c)){
sb.append(c);
found = true;
} else if(found){
// If we already found a digit before and this char is not a digit, stop looping
break;
}
}
return sb.toString();
}
예:
"123abc" 입력의 경우 위의 메서드는 123을 반환합니다.
abc1000def의 경우 1000.
'555abc45'의 경우, 555.
abc의 경우 빈 문자열을 반환합니다.
regex보다 빠르다고 생각합니다.
public final boolean containsDigit(String s) {
boolean containsDigit = false;
if (s != null && !s.isEmpty()) {
for (char c : s.toCharArray()) {
if (containsDigit = Character.isDigit(c)) {
break;
}
}
}
return containsDigit;
}
s=s.replaceAll("[*a-zA-Z]", "")
모든 알파벳을 바꿉니다.
s=s.replaceAll("[*0-9]", "")
모든 숫자를 바꿉니다.
위의 두 가지 대체를 수행하면 특수 문자열이 모두 표시됩니다.
에서 정수만 추출하는 경우String s=s.replaceAll("[^0-9]", "")
에서 알파벳만 추출하는 경우String s=s.replaceAll("[^a-zA-Z]", "")
해피 코딩 :)
패턴 하나 틀리지 않았어요.작고 달콤한 솔루션에 대해서는 아래 안내에 따라 주십시오.
String regex = "(.)*(\\d)(.)*";
Pattern pattern = Pattern.compile(regex);
String msg = "What is the square of 10?";
boolean containsNumber = pattern.matcher(msg).matches();
아래 코드는 "Check a String in Java"에 숫자가 포함되어 있는지 확인합니다.
Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");
if(m.find()){
System.out.println("Hello "+m.find());
}
Pattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);
제가 사용한 솔루션은 다음과 같습니다.
Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);
Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);
if (matcher1.find() && matcher2.find())
{
int number = Integer.parseInt(matcher1.group());
pw.println(number + " squared = " + (number * number));
}
완벽한 해결책은 아니지만, 제 욕구에 맞았습니다.도와주셔서 감사합니다.:)
다음의 패턴을 시험해 보겠습니다.
.matches("[a-zA-Z ]*\\d+.*")
아래 코드 조각은 문자열에 숫자가 포함되어 있는지 여부를 나타냅니다.
str.matches(".*\\d.*")
or
str.matches(.*[0-9].*)
예를들면
String str = "abhinav123";
str.matches(".*\\d.*") or str.matches(.*[0-9].*) will return true
str = "abhinav";
str.matches(".*\\d.*") or str.matches(.*[0-9].*) will return false
public String hasNums(String str) {
char[] nums = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] toChar = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
toChar[i] = str.charAt(i);
for (int j = 0; j < nums.length; j++) {
if (toChar[i] == nums[j]) { return str; }
}
}
return "None";
}
여기서 리다이렉트 되어 문자열의 디지트를 찾는 방법을 찾고 있습니다.Kotlin
언어, 코틀린만의 솔루션을 원하는 다른 분들을 위해 제 연구 결과를 여기에 남겨두겠습니다.
문자열에 숫자가 포함되어 있는지 확인:
val hasDigits = sampleString.any { it.isDigit() }
문자열에 숫자만 포함되어 있는지 확인:
val hasOnlyDigits = sampleString.all { it.isDigit() }
문자열에서 숫자 추출:
val onlyNumberString = sampleString.filter { it.isDigit() }
이거 드셔보세요
String text = "ddd123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
try {
double numVal = Double.valueOf(numOnly);
System.out.println(text +" contains numbers");
} catch (NumberFormatException e){
System.out.println(text+" not contains numbers");
}
숫자만 찾는 것이 아니라 추출도 하고 싶기 때문에 작은 함수를 쓰는 것이 좋습니다.숫자를 찾을 때까지 한 글자 한 글자 찾아라.아, 방금 stackoverflow에서 필요한 코드를 찾았습니다. 문자열에서 정수를 찾습니다.인정된 답을 보세요.
.matches(".*\\d+.*")
숫자만 사용할 수 있고 다른 기호들은 사용할 수 없습니다.//
또는*
기타.
ASCII 는 UNICODE 의 선두에 있기 때문에, 다음과 같이 할 수 있습니다.
(x >= 97 && x <= 122) || (x >= 65 && x <= 90) // 97 == 'a' and 65 = 'A'
다른 가치도 알아낼 수 있을 거야
언급URL : https://stackoverflow.com/questions/18590901/check-and-extract-a-number-from-a-string-in-java
'programing' 카테고리의 다른 글
문자열의 일부만 제거하지만 문자열 끝에 있는 경우에만 제거 (0) | 2022.10.28 |
---|---|
MariaDB와 MySQL을 PHP 스크립트에서 어떻게 구별합니까? (0) | 2022.10.28 |
XAMPP로 루트 암호를 변경한 후 MySQL을 시작할 수 없습니다. (0) | 2022.10.28 |
어레이를 재인덱스화하는 방법 (0) | 2022.10.18 |
특정 ID에 적합한 데이터 가져오기 (0) | 2022.10.18 |