반응형
무선의 첫 문자가 숫자인지 어떻게 알 수 있습니까?
Java에서 멀티미디어의 첫 번째 문자가 숫자인지 알아내는 방법이 있습니까?
한 가지 방법은
string.startsWith("1")
9 시까 지 위의 작업을 수행하지만 매우 비효율적 인 것입니다.
Character.isDigit(string.charAt(0))
참고 이 수 있는 유니 코드 숫자 만이 아니라 0-9. 다음을 선호 할 수 있습니다.
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
또는 더 느린 정규식 솔루션 :
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
그러나 반드시 있어야하는 방법을 사용하여 있어야합니다. 이 경우, charAt(0)
및 substring(0, 1)
을 던질 것이다 StringIndexOutOfBoundsException
. startsWith
이 문제가 없습니다.
전체 조건을 한 줄로 만들고 길이 확인을 피 예상 정규식을 다음과 같이 설명 수 있습니다.
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
조건이 프로그램에서 루프에 말하는 정규식 사용에 대한 작은 성능이 눈에 타이트 할 것입니다.
정규 작업은 매우 강력하지만 비용이 많이 많이 사용 도구입니다. 첫 번째 문자가 숫자인지 확인하는 데 사용하는 것은 유효하지만 그렇게 우아합니다. :)이 방법을 선호합니다.
public boolean isLeadingDigit(final String value){
final char c = value.charAt(0);
return (c >= '0' && c <= '9');
}
regular expression starts with number->'^[0-9]'
Pattern pattern = Pattern.compile('^[0-9]');
Matcher matcher = pattern.matcher(String);
if(matcher.find()){
System.out.println("true");
}
나는 방금이 질문을하고 정규식을 사용하는 솔루션으로 기여할 생각을했습니다.
제 경우에는 도우미 메서드를 사용합니다.
public boolean notNumber(String input){
boolean notNumber = false;
try {
// must not start with a number
@SuppressWarnings("unused")
double checker = Double.valueOf(input.substring(0,1));
}
catch (Exception e) {
notNumber = true;
}
return notNumber;
}
아마도 과잉이지만 가능한 한 정규식을 피하려고 노력합니다.
반응형
'IT' 카테고리의 다른 글
버전 관리를 위해 태그와 릴리스 / 베타 관리를위한 이유는 무엇입니까? (0) | 2020.08.07 |
---|---|
Rails : 두 열의 고유성 확인 (함께) (0) | 2020.08.07 |
이 프로젝트에 OutputPath 속성이 설정되어 있지 않습니다. (0) | 2020.08.07 |
http.Get에서 JSON 응답을 얻는 방법 (0) | 2020.08.07 |
Android Studio 1.0 및 '라이브러리 프로젝트에서 applicationId를 수 없음'오류 (0) | 2020.08.07 |