Java에서 문자열이 숫자인지 확인하는 방법
문자열이 숫자인지 아닌지를 구문 분석하기 전에 어떻게 확인하시겠습니까?
이 작업은 일반적으로 간단한 사용자 정의 기능(즉, "isNumeric" 롤 사용자 정의 기능)을 사용하여 수행됩니다.
예를 들어 다음과 같습니다.
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
단, 이 함수를 많이 호출하고 숫자가 아니기 때문에 많은 체크가 실패할 것으로 예상할 경우 이 메커니즘의 퍼포먼스는 그다지 좋지 않습니다.이는 각 장애에 대해 예외가 발생하는 것에 의존하기 때문입니다.이는 상당히 비용이 많이 들기 때문입니다.
다른 방법으로는 정규식을 사용하여 숫자가 유효한지 확인하는 방법이 있습니다.
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
다만, 아랍어 이외의 숫자(0~9 이외의 숫자)를 사용하고 있는 경우는, 실패하기 때문에, 상기의 RegEx 메카니즘에 주의해 주세요.이는 RegEx의 \d 부분은 [0-9]에만 일치하며 국제적으로 수치적으로 인식되지 않기 때문입니다.(이 점을 지적해 주신 오리건 고스트 씨 덕분입니다.)
또는 Java의 기본 제공 java.text를 사용하는 방법도 있습니다.NumberFormat 객체: 문자열을 해석한 후 파서 위치가 문자열 끝에 있는지 확인합니다.이 경우 문자열 전체가 숫자라고 가정할 수 있습니다.
public static boolean isNumeric(String str) {
ParsePosition pos = new ParsePosition(0);
NumberFormat.getInstance().parse(str, pos);
return str.length() == pos.getIndex();
}
Apache Commons Lang 3.5 이후: 또는
Apache Commons Lang 3.4 이하: 또는
어떤 반환을 사용할 수도 있습니다.true
빈 문자열의 경우 문자열의 내부 공간을 무시합니다.다른 방법은 기본적으로 숫자를 체크하는 를 Java에 따라 해석할 수 있다는 것입니다(링크된 javadoc에는 각 메서드의 자세한 예가 포함되어 있습니다).
Android를 사용하는 경우 다음을 사용해야 합니다.
android.text.TextUtils.isDigitsOnly(CharSequence str)
심플하게 해 주세요.대부분의 경우는, 「재프로그래밍」(같은 것)할 수 있습니다.
Java 8 람다 식
String someString = "123123";
boolean isNumeric = someString.chars().allMatch( Character::isDigit );
TP가 그의 훌륭한 답변에서 언급했듯이, 저도 예외로 문자열이 숫자인지 아닌지를 테스트하는 것에 대해 비슷한 성능 문제가 있습니다.그래서 결국 줄을 쪼개서java.lang.Character.isDigit()
.
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
}
자바독에 따르면Character.isDigit(char)
의지하다퍼포먼스 면에서는 단순한 N개수의 비교(N은 문자열 내의 문자수)가 regex 매칭을 하는 것보다 계산적으로 효율적이라고 생각합니다.
업데이트: Jean-Franchois Corbett가 코멘트한 바와 같이, 위의 코드는 저의 사용 사례의 대부분을 커버하는 양의 정수만을 검증합니다.다음은 시스템에서 사용되는 기본 로케일에 따라 10진수를 올바르게 검증하는 업데이트된 코드입니다.단, 10진수 구분은 문자열 내에서1회만 발생한다고 가정합니다.
public static boolean isStringNumeric( String str )
{
DecimalFormatSymbols currentLocaleSymbols = DecimalFormatSymbols.getInstance();
char localeMinusSign = currentLocaleSymbols.getMinusSign();
if ( !Character.isDigit( str.charAt( 0 ) ) && str.charAt( 0 ) != localeMinusSign ) return false;
boolean isDecimalSeparatorFound = false;
char localeDecimalSeparator = currentLocaleSymbols.getDecimalSeparator();
for ( char c : str.substring( 1 ).toCharArray() )
{
if ( !Character.isDigit( c ) )
{
if ( c == localeDecimalSeparator && !isDecimalSeparatorFound )
{
isDecimalSeparatorFound = true;
continue;
}
return false;
}
}
return true;
}
구글 구아바Ints.tryParse
Integer.parseInt
그것은 되돌아온다.null
문자열이 유효한 정수로 해석되지 않는 경우 예외를 슬로우하지 않습니다.Integer가 int으로 .integer는 Integer/Integer로 변환/자동상자를 반환해야 합니다.
예:
String s1 = "22";
String s2 = "22.2";
Integer oInt1 = Ints.tryParse(s1);
Integer oInt2 = Ints.tryParse(s2);
int i1 = -1;
if (oInt1 != null) {
i1 = oInt1.intValue();
}
int i2 = -1;
if (oInt2 != null) {
i2 = oInt2.intValue();
}
System.out.println(i1); // prints 22
System.out.println(i2); // prints -1
그러나 현재 릴리스인 Guava r11에서는 여전히 @Beta 마크가 붙어 있습니다.
벤치마킹은 안 해봤어요., 오버헤드가 만, 으로는 「」를 사용하고 .Character.digit(string.charAt(idx))
위의 @Ibrahim의 답변과 비슷하지만 약간 다릅니다.이러한 구현에서 오버헤드를 처리하는 것은 예외는 없습니다.
값의 유효성을 확인하기 위해 예외를 사용하지 마십시오.대신 apache Number Utils와 같은 Utillibs를 사용합니다.
NumberUtils.isNumber(myStringValue);
편집:
문자열이 0으로 시작하는 경우 NumberUtils는 값을 16진수로 해석합니다.
NumberUtils.isNumber("07") //true
NumberUtils.isNumber("08") //false
왜 모두가 예외/정규 솔루션을 요구하고 있는가?
대부분의 사람들이 try/catch를 사용하는 것은 괜찮지만, 자주 사용하고 싶다면...굉장히 부담스러울 수 있어요.
여기서 한 것은 regex, parseNumber() 메서드 및 배열 검색 메서드를 사용하여 어떤 것이 가장 효율적인지 확인하는 것입니다.이번에는 정수만 봤어요.
public static boolean isNumericRegex(String str) {
if (str == null)
return false;
return str.matches("-?\\d+");
}
public static boolean isNumericArray(String str) {
if (str == null)
return false;
char[] data = str.toCharArray();
if (data.length <= 0)
return false;
int index = 0;
if (data[0] == '-' && data.length > 1)
index = 1;
for (; index < data.length; index++) {
if (data[index] < '0' || data[index] > '9') // Character.isDigit() can go here too.
return false;
}
return true;
}
public static boolean isNumericException(String str) {
if (str == null)
return false;
try {
/* int i = */ Integer.parseInt(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
얻은 속도 결과는 다음과 같습니다.
Done with: for (int i = 0; i < 10000000; i++)...
With only valid numbers ("59815833" and "-59815833"):
Array numeric took 395.808192 ms [39.5808192 ns each]
Regex took 2609.262595 ms [260.9262595 ns each]
Exception numeric took 428.050207 ms [42.8050207 ns each]
// Negative sign
Array numeric took 355.788273 ms [35.5788273 ns each]
Regex took 2746.278466 ms [274.6278466 ns each]
Exception numeric took 518.989902 ms [51.8989902 ns each]
// Single value ("1")
Array numeric took 317.861267 ms [31.7861267 ns each]
Regex took 2505.313201 ms [250.5313201 ns each]
Exception numeric took 239.956955 ms [23.9956955 ns each]
// With Character.isDigit()
Array numeric took 400.734616 ms [40.0734616 ns each]
Regex took 2663.052417 ms [266.3052417 ns each]
Exception numeric took 401.235906 ms [40.1235906 ns each]
With invalid characters ("5981a5833" and "a"):
Array numeric took 343.205793 ms [34.3205793 ns each]
Regex took 2608.739933 ms [260.8739933 ns each]
Exception numeric took 7317.201775 ms [731.7201775 ns each]
// With a single character ("a")
Array numeric took 291.695519 ms [29.1695519 ns each]
Regex took 2287.25378 ms [228.725378 ns each]
Exception numeric took 7095.969481 ms [709.5969481 ns each]
With null:
Array numeric took 214.663834 ms [21.4663834 ns each]
Regex took 201.395992 ms [20.1395992 ns each]
Exception numeric took 233.049327 ms [23.3049327 ns each]
Exception numeric took 6603.669427 ms [660.3669427 ns each] if there is no if/null check
면책사항:이 방법이 100% 최적화되어 있다고 주장하는 것은 아닙니다.데이터의 데모를 위해서입니다.
예외는 숫자가 4자 이하이고 모든 문자열이 항상 숫자일 경우에만 획득됩니다.그런데 왜 수표를 가지고 있죠?
즉, 시행/캐치 중에 잘못된 숫자를 자주 발견하면 매우 고통스럽다는 것입니다.제가 항상 지키는 중요한 규칙은 프로그램 흐름에 절대 try/catch를 사용하지 않는 것입니다.이것이 그 이유의 예시입니다.
흥미롭게도 심플한 if char <0 | >9은 매우 쓰기 쉽고 기억하기 쉬우며(또한 여러 언어로 동작해야 합니다), 거의 모든 테스트 시나리오에서 승리합니다.
유일한 단점은 Integer.parseInt()는 ASCII 이외의 번호를 처리할 수 있지만 어레이 검색 방식에서는 처리할 수 없다는 것입니다.
내가 왜 문자 배열 1을 기억하기 쉽다고 말했는지 궁금하다면, 부정적인 부호가 없다는 것을 알면 다음과 같이 응축된 것을 쉽게 피할 수 있다.
public static boolean isNumericArray(String str) {
if (str == null)
return false;
for (char c : str.toCharArray())
if (c < '0' || c > '9')
return false;
return true;
마지막으로, 저는 모든 표를 올린 상태에서 접수된 사례의 할당 운영자가 궁금했습니다.할당에 추가
double d = Double.parseDouble(...)
값을 사용하지 않기 때문에 쓸모가 없을 뿐만 아니라 처리 시간을 낭비하고 실행 시간을 몇 나노초 증가시킵니다(그 결과 테스트에서 100~200밀리초 증가).사실 성능 저하를 위한 추가 작업이기 때문에 누가 왜 그렇게 하는지 알 수 없습니다.
그게 최적화 될 거라고 생각하겠지만...바이트 코드를 체크하고 컴파일러가 무엇을 하는지 봐야 할 것 같습니다.그게 왜 항상 더 길쭉하게 보이는지는 설명되지 않지만, 만약 그것이 최적화된다면...무슨 일일까?메모:길이가 길수록 10000,000회 반복 테스트를 실행하고 해당 프로그램을 여러 번(10x+) 실행하면 항상 느린 것으로 나타났습니다.
편집: Character.isDigit() 테스트를 갱신했습니다.
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(.\\d+)?");
}
CraigTP의 정규식(상기 참조)은 몇 가지 잘못된 긍정을 생성합니다.예: '.'가 소수점이 아닌 모든 문자와 일치하므로 "23y4"는 숫자로 계산됩니다.
또한 선두가 '+'인 숫자는 거부됩니다.
이 두 가지 사소한 문제를 피하기 위한 대안은 다음과 같습니다.
public static boolean isNumeric(String str)
{
return str.matches("[+-]?\\d*(\\.\\d+)?");
}
지정된 문자열의 모든 숫자를 공백("")으로 대체하여 문자열 길이가 0일 경우 지정된 문자열에 숫자만 포함된다고 할 수 있습니다.예:
boolean isNumber(String str){
if(str.length() == 0)
return false; //To check if string is empty
if(str.charAt(0) == '-')
str = str.replaceFirst("-","");// for handling -ve numbers
System.out.println(str);
str = str.replaceFirst("\\.",""); //to check if it contains more than one decimal points
if(str.length() == 0)
return false; // to check if it is empty string after removing -ve sign and decimal point
System.out.println(str);
return str.replaceAll("[0-9]","").length() == 0;
}
다음을 사용할 수 있습니다.
try
{
NumberFormat.getInstance().parse(value);
}
catch(ParseException e)
{
// Not a number.
}
Java를 사용하여 Android 앱을 개발하는 경우 TextUtils.isDigits를 사용할 수 있습니다.기능만.
여기 그 문제에 대한 나의 답이 있었다.
사용하여 을 해석하기 할 수 있는 편의 :isParsable(Object parser, String str)
는 「」로 할 수 Class
★★★object
를 들면 「:」, 「예:」, 「예:」, 「예:」, 「예: 「예:」, 「예:」, 「예: 「예:」, 「예: 「예:」, 「예:」와 , 「예:」를 할 수 .이러한 커스텀 파서는, 다음과 같은 시나리오에서도 사용할 수 있습니다.
isParsable(Integer.class, "11");
isParsable(Double.class, "11.11");
Object dateFormater = new java.text.SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
isParsable(dateFormater, "2001.07.04 AD at 12:08:56 PDT");
여기 내 코드와 방법 설명이 있습니다.
import java.lang.reflect.*;
/**
* METHOD: isParsable<p><p>
*
* This method will look through the methods of the specified <code>from</code> parameter
* looking for a public method name starting with "parse" which has only one String
* parameter.<p>
*
* The <code>parser</code> parameter can be a class or an instantiated object, eg:
* <code>Integer.class</code> or <code>new Integer(1)</code>. If you use a
* <code>Class</code> type then only static methods are considered.<p>
*
* When looping through potential methods, it first looks at the <code>Class</code> associated
* with the <code>parser</code> parameter, then looks through the methods of the parent's class
* followed by subsequent ancestors, using the first method that matches the criteria specified
* above.<p>
*
* This method will hide any normal parse exceptions, but throws any exceptions due to
* programmatic errors, eg: NullPointerExceptions, etc. If you specify a <code>parser</code>
* parameter which has no matching parse methods, a NoSuchMethodException will be thrown
* embedded within a RuntimeException.<p><p>
*
* Example:<br>
* <code>isParsable(Boolean.class, "true");<br>
* isParsable(Integer.class, "11");<br>
* isParsable(Double.class, "11.11");<br>
* Object dateFormater = new java.text.SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");<br>
* isParsable(dateFormater, "2001.07.04 AD at 12:08:56 PDT");<br></code>
* <p>
*
* @param parser The Class type or instantiated Object to find a parse method in.
* @param str The String you want to parse
*
* @return true if a parse method was found and completed without exception
* @throws java.lang.NoSuchMethodException If no such method is accessible
*/
public static boolean isParsable(Object parser, String str) {
Class theClass = (parser instanceof Class? (Class)parser: parser.getClass());
boolean staticOnly = (parser == theClass), foundAtLeastOne = false;
Method[] methods = theClass.getMethods();
// Loop over methods
for (int index = 0; index < methods.length; index++) {
Method method = methods[index];
// If method starts with parse, is public and has one String parameter.
// If the parser parameter was a Class, then also ensure the method is static.
if(method.getName().startsWith("parse") &&
(!staticOnly || Modifier.isStatic(method.getModifiers())) &&
Modifier.isPublic(method.getModifiers()) &&
method.getGenericParameterTypes().length == 1 &&
method.getGenericParameterTypes()[0] == String.class)
{
try {
foundAtLeastOne = true;
method.invoke(parser, str);
return true; // Successfully parsed without exception
} catch (Exception exception) {
// If invoke problem, try a different method
/*if(!(exception instanceof IllegalArgumentException) &&
!(exception instanceof IllegalAccessException) &&
!(exception instanceof InvocationTargetException))
continue; // Look for other parse methods*/
// Parse method refuses to parse, look for another different method
continue; // Look for other parse methods
}
}
}
// No more accessible parse method could be found.
if(foundAtLeastOne) return false;
else throw new RuntimeException(new NoSuchMethodException());
}
/**
* METHOD: willParse<p><p>
*
* A convienence method which calls the isParseable method, but does not throw any exceptions
* which could be thrown through programatic errors.<p>
*
* Use of {@link #isParseable(Object, String) isParseable} is recommended for use so programatic
* errors can be caught in development, unless the value of the <code>parser</code> parameter is
* unpredictable, or normal programtic exceptions should be ignored.<p>
*
* See {@link #isParseable(Object, String) isParseable} for full description of method
* usability.<p>
*
* @param parser The Class type or instantiated Object to find a parse method in.
* @param str The String you want to parse
*
* @return true if a parse method was found and completed without exception
* @see #isParseable(Object, String) for full description of method usability
*/
public static boolean willParse(Object parser, String str) {
try {
return isParsable(parser, str);
} catch(Throwable exception) {
return false;
}
}
ASCII 숫자만 포함하는 양의 base-10 정수만 일치시키려면 다음 명령을 사용합니다.
public static boolean isNumeric(String maybeNumeric) {
return maybeNumeric != null && maybeNumeric.matches("[0-9]+");
}
트라이캐치를 피하고 음수 및 과학적 표기법을 처리하는 뛰어난 성능의 접근법.
Pattern PATTERN = Pattern.compile( "^(-?0|-?[1-9]\\d*)(\\.\\d+)?(E\\d+)?$" );
public static boolean isNumeric( String value )
{
return value != null && PATTERN.matcher( value ).matches();
}
정규식 매칭
다음으로 업그레이드된 "CraigTP" regex 매칭과 더 많은 검증을 수행하는 예를 제시하겠습니다.
public static boolean isNumeric(String str)
{
return str.matches("^(?:(?:\\-{1})?\\d+(?:\\.{1}\\d+)?)$");
}
- 음수 부호는 하나만 허용되며 시작 부분에 있어야 합니다.
- 음수 기호 뒤에는 숫자가 있어야 합니다.
- 소수점은 1개만 사용할 수 있습니다.
- 소수점 뒤에 숫자가 있어야 합니다.
정규식 테스트
1 -- **VALID**
1. -- INVALID
1.. -- INVALID
1.1 -- **VALID**
1.1.1 -- INVALID
-1 -- **VALID**
--1 -- INVALID
-1. -- INVALID
-1.1 -- **VALID**
-1.1.1 -- INVALID
문자열이 숫자인지 확인하기 위한 수업입니다.숫자 문자열도 수정됩니다.
특징:
- 불필요한 제로 삭제 ["12.0000000" -> "12"]
- 불필요한 제로 삭제 ["12.0580000" -> "12.058"]
- 숫자가 아닌 문자를 삭제합니다 ["12.00sdfsdf00" -> "12"]
- 마이너스 문자열 값 [-12,020000]-> -12.02]를 처리합니다.
- 여러 개의 도트를 삭제합니다[ - 12 . 0 . 20 . 000 " - > - 12 . 02 " ]
- 추가 라이브러리 없이 표준 Java만 지원
여기 있습니다...
public class NumUtils {
/**
* Transforms a string to an integer. If no numerical chars returns a String "0".
*
* @param str
* @return retStr
*/
static String makeToInteger(String str) {
String s = str;
double d;
d = Double.parseDouble(makeToDouble(s));
int i = (int) (d + 0.5D);
String retStr = String.valueOf(i);
System.out.printf(retStr + " ");
return retStr;
}
/**
* Transforms a string to an double. If no numerical chars returns a String "0".
*
* @param str
* @return retStr
*/
static String makeToDouble(String str) {
Boolean dotWasFound = false;
String orgStr = str;
String retStr;
int firstDotPos = 0;
Boolean negative = false;
//check if str is null
if(str.length()==0){
str="0";
}
//check if first sign is "-"
if (str.charAt(0) == '-') {
negative = true;
}
//check if str containg any number or else set the string to '0'
if (!str.matches(".*\\d+.*")) {
str = "0";
}
//Replace ',' with '.' (for some european users who use the ',' as decimal separator)
str = str.replaceAll(",", ".");
str = str.replaceAll("[^\\d.]", "");
//Removes the any second dots
for (int i_char = 0; i_char < str.length(); i_char++) {
if (str.charAt(i_char) == '.') {
dotWasFound = true;
firstDotPos = i_char;
break;
}
}
if (dotWasFound) {
String befDot = str.substring(0, firstDotPos + 1);
String aftDot = str.substring(firstDotPos + 1, str.length());
aftDot = aftDot.replaceAll("\\.", "");
str = befDot + aftDot;
}
//Removes zeros from the begining
double uglyMethod = Double.parseDouble(str);
str = String.valueOf(uglyMethod);
//Removes the .0
str = str.replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2");
retStr = str;
if (negative) {
retStr = "-"+retStr;
}
return retStr;
}
static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
}
예외는 비용이 많이 들지만, 이 경우 RegEx는 훨씬 더 오래 걸립니다.다음 코드는 두 가지 함수의 간단한 테스트를 보여줍니다. 하나는 예외를 사용하는 함수이고 다른 하나는 regex를 사용하는 함수입니다.제 기계에서는 RegEx 버전이 예외보다 10배 느립니다.
import java.util.Date;
public class IsNumeric {
public static boolean isNumericOne(String s) {
return s.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
public static boolean isNumericTwo(String s) {
try {
Double.parseDouble(s);
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String [] args) {
String test = "12345.F";
long before = new Date().getTime();
for(int x=0;x<1000000;++x) {
//isNumericTwo(test);
isNumericOne(test);
}
long after = new Date().getTime();
System.out.println(after-before);
}
}
// 아래 코드를 확인하십시오.
public static boolean isDigitsOnly(CharSequence str) {
final int len = str.length();
for (int i = 0; i < len; i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
java.util을 사용할 수 있습니다.스캐너 오브젝트
public static boolean isNumeric(String inputData) {
Scanner sc = new Scanner(inputData);
return sc.hasNextInt();
}
// only int
public static boolean isNumber(int num)
{
return (num >= 48 && c <= 57); // 0 - 9
}
// is type of number including . - e E
public static boolean isNumber(String s)
{
boolean isNumber = true;
for(int i = 0; i < s.length() && isNumber; i++)
{
char c = s.charAt(i);
isNumber = isNumber & (
(c >= '0' && c <= '9') || (c == '.') || (c == 'e') || (c == 'E') || (c == '')
);
}
return isInteger;
}
// is type of number
public static boolean isInteger(String s)
{
boolean isInteger = true;
for(int i = 0; i < s.length() && isInteger; i++)
{
char c = s.charAt(i);
isInteger = isInteger & ((c >= '0' && c <= '9'));
}
return isInteger;
}
public static boolean isNumeric(String s)
{
try
{
Double.parseDouble(s);
return true;
}
catch (Exception e)
{
return false;
}
}
이 체크의 간단한 예를 다음에 나타냅니다.
public static boolean isNumericString(String input) {
boolean result = false;
if(input != null && input.length() > 0) {
char[] charArray = input.toCharArray();
for(char c : charArray) {
if(c >= '0' && c <= '9') {
// it is a digit
result = true;
} else {
result = false;
break;
}
}
}
return result;
}
API를 사용하지 않고 숫자와 소수점을 확인하는 몇 가지 조건을 설명했습니다.
길이 1자리 숫자 고정 확인
Character.isDigit(char)
길이 고정 번호 확인(전제 길이는 6)
String number = "132452";
if(number.matches("([0-9]{6})"))
System.out.println("6 digits number identified");
[ Variable Length number ](변화 길이 4 ~6으로 가정) 체크
// {n,m} n <= length <= m
String number = "132452";
if(number.matches("([0-9]{4,6})"))
System.out.println("Number Identified between 4 to 6 length");
String number = "132";
if(!number.matches("([0-9]{4,6})"))
System.out.println("Number not in length range or different format");
[ Variable Length ]체크박스를 켜겠습니다(4~7의 길이로 가정).
// It will not count the '.' (Period) in length
String decimal = "132.45";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");
String decimal = "1.12";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");
String decimal = "1234";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");
String decimal = "-10.123";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");
String decimal = "123..4";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");
String decimal = "132";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");
String decimal = "1.1";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");
많은 사람에게 도움이 되길 바랍니다.
다른 답변을 바탕으로 제가 직접 작성했습니다.패턴이나 구문 분석(예외 체크 포함)을 사용하지 않습니다.
최대 1개의 마이너스 기호와 최대 1개의 소수점을 확인합니다.
다음은 몇 가지 예시와 그 결과를 제시하겠습니다.
"1", "-1", "-1.5" 및 "-1.556"은 true를 반환합니다.
"1..5", "1A.5", "1.5D", "-" 및 "-1"은 false를 반환합니다.
주의: 필요에 따라 Locale 파라미터를 받아들여 DecimalFormatSymbols.getInstance() 호출에 전달하여 현재 Locale이 아닌 특정 Locale을 사용할 수 있습니다.
public static boolean isNumeric(final String input) {
//Check for null or blank string
if(input == null || input.isBlank()) return false;
//Retrieve the minus sign and decimal separator characters from the current Locale
final var localeMinusSign = DecimalFormatSymbols.getInstance().getMinusSign();
final var localeDecimalSeparator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
//Check if first character is a minus sign
final var isNegative = input.charAt(0) == localeMinusSign;
//Check if string is not just a minus sign
if (isNegative && input.length() == 1) return false;
var isDecimalSeparatorFound = false;
//If the string has a minus sign ignore the first character
final var startCharIndex = isNegative ? 1 : 0;
//Check if each character is a number or a decimal separator
//and make sure string only has a maximum of one decimal separator
for (var i = startCharIndex; i < input.length(); i++) {
if(!Character.isDigit(input.charAt(i))) {
if(input.charAt(i) == localeDecimalSeparator && !isDecimalSeparatorFound) {
isDecimalSeparatorFound = true;
} else return false;
}
}
return true;
}
크레이그를 수정했습니다.과학적 표기법과 점과 쉼표를 모두 소수 구분자로 받아들이는 TP의 솔루션
^-?\d+([,\.]\d+)?([eE]-?\d+)?$
예
var re = new RegExp("^-?\d+([,\.]\d+)?([eE]-?\d+)?$");
re.test("-6546"); // true
re.test("-6546355e-4456"); // true
re.test("-6546.355e-4456"); // true, though debatable
re.test("-6546.35.5e-4456"); // false
re.test("-6546.35.5e-4456.6"); // false
그래서 에서의 Try* 접근법이 좋습니다.NET. Java와 같은 기존 Parse 방식 외에 TryParse 방식도 있습니다.저는 Java 구문을 잘 못하기 때문에(파라미터 아웃?) 다음 것을 의사 코드로 취급해 주세요.하지만 컨셉은 명확해야 합니다.
boolean parseInteger(String s, out int number)
{
try {
number = Integer.parseInt(myString);
return true;
} catch(NumberFormatException e) {
return false;
}
}
사용방법:
int num;
if (parseInteger("23", out num)) {
// Do something with num.
}
해석(즉, 와 함께)하고 예외를 검출하기만 하면 됩니다.=)
명확히 하기 위해:해석int 함수는 어떤 경우든 번호를 해석할 수 있는지(분명히) 체크합니다.또한 해석할 경우 실제로 해석함으로써 퍼포먼스에 영향을 주지 않습니다.
해석하지 않는 경우(또는 매우 드물게 해석하는 경우)는 물론 다른 방법으로 해석하는 것이 좋습니다.
Apache Commons Lang에서 NumberUtils.isCreatable()을 사용할 수 있습니다.
NumberUtils.isNumber는 4.0에서는 폐지되므로 대신 NumberUtils.isCreatable()을 사용합니다.
Java 8 Stream, 람다 표현, 기능 인터페이스
처리된 모든 케이스(문자열 null, 문자열 비어 있음 등)
String someString = null; // something="", something="123abc", something="123123"
boolean isNumeric = Stream.of(someString)
.filter(s -> s != null && !s.isEmpty())
.filter(Pattern.compile("\\D").asPredicate().negate())
.mapToLong(Long::valueOf)
.boxed()
.findAny()
.isPresent();
문자열이 숫자인지 확실하게 알 수 있는 유일한 방법은 그것을 해석하는 것이라고 생각합니다.그래서 그냥 해석해보고 숫자면 int에 무료로 번호를 받을 수 있어요!
언급URL : https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java
'sourcecode' 카테고리의 다른 글
Vue.js 라이브러리를 가져오는 것과 Vue-CLI를 통해 설치하는 것의 차이점은 무엇입니까? (0) | 2022.08.30 |
---|---|
String Builder에 새 줄을 추가하는 방법 (0) | 2022.08.30 |
VeValidate 연결 메서드: 필드에 이름이 있는 경우 필드에 "name" 또는 "data-vv-name" 속성이 없습니다. (0) | 2022.08.30 |
base64 이미지의 v-card-media (0) | 2022.08.29 |
목록을 알파벳 순으로 정렬하려면 어떻게 해야 합니까? (0) | 2022.08.29 |