Java에서 문자열에 숫자 만 포함되어 있는지 확인하는 방법
이 질문에는 이미 답변이 있습니다.
Java for String 클래스에는 matches라는 메소드가 있습니다.이 메소드를 사용하여 문자열에 정규 표현식을 사용하여 숫자 만 있는지 확인하는 방법이 있습니다. 아래 예제를 사용하여 시도했지만 둘 다 결과로 거짓을 반환했습니다.
String regex = "[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
String regex = "^[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
시험
String regex = "[0-9]+";
또는
String regex = "\\d+";
자바에 따라 정규 표현식 의 +
수단 "한 번 이상"과 \d
수단 "숫자".
참고 : "double backslash"는 단일 백 슬래시를 얻기 위한 이스케이프 시퀀스입니다. 따라서 \\d
Java String에서는 실제 결과를 제공합니다.\d
참고 문헌 :
편집 : 다른 답변에 약간의 혼란으로 인해 테스트 사례를 작성 중이며 더 자세한 내용을 설명합니다.
먼저,이 솔루션 (또는 다른 솔루션)의 정확성이 확실하지 않은 경우이 테스트 케이스를 실행하십시오.
String regex = "\\d+";
// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));
// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));
질문 1:
정규식 을 추가
^
하고 추가 할 필요$
가 없으므로 "aa123bb"와 일치하지 않습니까?
제 자바에서은 matches
(질문에 지정된) 메소드는 전체 문자열이 아닌 조각을 일치합니다. 다시 말해, 사용할 필요는 없습니다 ^\\d+$
(정확하더라도). 마지막 부정적인 테스트 사례를 참조하십시오.
온라인 "정규 검사기"를 사용하는 경우 다르게 동작 할 수 있습니다. Java에서 문자열 조각을 일치시키기 위해 find
여기에 자세히 설명 된 방법을 대신 사용할 수 있습니다.
Java Regex에서 matches ()와 find ()의 차이점
질문 2 :
이 정규식도 빈 문자열과 일치하지
""
않습니까?
아니요 . 정규식 \\d*
은 빈 문자열과 일치하지만 일치 \\d+
하지 않습니다. 별 *
은 0 이상을 의미하고 더하기 +
는 하나 이상을 의미합니다. 첫 번째 부정적인 테스트 사례를 참조하십시오.
질문 3
정규식 패턴을 컴파일하는 것이 더 빠르지 않습니까?
예. 를 호출 할 때마다 정규 표현식 패턴을 한 번만 컴파일하는 것이 더 빠르 matches
므로 성능 관련 사항이 중요한 경우 다음 Pattern
과 같이 컴파일하여 사용할 수 있습니다.
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());
Apache Commons에서 NumberUtil.isNumber (String str) 를 사용할 수도 있습니다.
아직 게시되지 않은 솔루션 하나 더 :
String regex = "\\p{Digit}+"; // uses POSIX character class
Long.parseLong(data)
예외를 잡으면 빼기 부호를 처리합니다.
자릿수는 제한되어 있지만 실제로 사용할 수있는 데이터 변수를 만듭니다. 즉 가장 일반적인 유스 케이스입니다.
다음과 같이 숫자 ( +
기호) 이상을 허용해야합니다 .
String regex = "[0-9]+";
String data = "23343453";
System.out.println(data.matches(regex));
정규식을 사용하면 성능면에서 비용이 많이 듭니다. 문자열을 긴 값으로 구문 분석하는 것은 비효율적이고 신뢰할 수 없으며 필요하지 않을 수 있습니다.
What I suggest is to simply check if each character is a digit, what can be efficiently done using Java 8 lambda expressions:
boolean isNumeric = someString.chars().allMatch(x -> Character.isDigit(x));
According to Oracle's Java Documentation:
private static final Pattern NUMBER_PATTERN = Pattern.compile(
"[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
"([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
"(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
"[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
boolean isNumber(String s){
return NUMBER_PATTERN.matcher(s).matches()
}
We can use either Pattern.compile("[0-9]+.[0-9]+")
or Pattern.compile("\\d+.\\d+")
. They have the same meaning.
the pattern [0-9] means digit. The same as '\d'. '+' means it appears more times. '.' for integer or float.
Try following code:
import java.util.regex.Pattern;
public class PatternSample {
public boolean containNumbersOnly(String source){
boolean result = false;
Pattern pattern = Pattern.compile("[0-9]+.[0-9]+"); //correct pattern for both float and integer.
pattern = Pattern.compile("\\d+.\\d+"); //correct pattern for both float and integer.
result = pattern.matcher(source).matches();
if(result){
System.out.println("\"" + source + "\"" + " is a number");
}else
System.out.println("\"" + source + "\"" + " is a String");
return result;
}
public static void main(String[] args){
PatternSample obj = new PatternSample();
obj.containNumbersOnly("123456.a");
obj.containNumbersOnly("123456 ");
obj.containNumbersOnly("123456");
obj.containNumbersOnly("0123456.0");
obj.containNumbersOnly("0123456a.0");
}
}
Output:
"123456.a" is a String
"123456 " is a String
"123456" is a number
"0123456.0" is a number
"0123456a.0" is a String
Try this part of code:
void containsOnlyNumbers(String str)
{
try {
Integer num = Integer.valueOf(str);
System.out.println("is a number");
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("is not a number");
}
}
참고URL : https://stackoverflow.com/questions/15111420/how-to-check-if-a-string-contains-only-digits-in-java
'IT story' 카테고리의 다른 글
Visual Studio Code의 스크롤 막대 / 미니 맵을 비활성화하거나 숨기는 방법은 무엇입니까? (0) | 2020.06.26 |
---|---|
Ruby에서 두 Date 객체 사이의 일 수를 어떻게 찾을 수 있습니까? (0) | 2020.06.26 |
jQuery는 스크롤에 더 많은 데이터를로드 (0) | 2020.06.26 |
선형 레이아웃 안에 내용을 배치하는 방법은 무엇입니까? (0) | 2020.06.26 |
하나를 제외한 모든 파일 이동 (0) | 2020.06.26 |