Wie würden Sie prüfen, ob ein String eine Zahl ist, bevor Sie ihn parsen?
Biete eine Bearbeitung an - .getInstance() fehlte. +1 als dies war die Antwort, die ich ging mit, wenn diese Frage zu finden.
Wie würden Sie prüfen, ob ein String eine Zahl ist, bevor Sie ihn parsen?
Sie können verwenden NumberFormat#parse
:
try
{
NumberFormat.getInstance().parse(value);
}
catch(ParseException e)
{
// Not a number.
}
Biete eine Bearbeitung an - .getInstance() fehlte. +1 als dies war die Antwort, die ich ging mit, wenn diese Frage zu finden.
Wenn Sie Java zur Entwicklung einer Android-Anwendung verwenden, können Sie mit TextUtils.isDigitsOnly Funktion.
Hier war meine Antwort auf das Problem.
Eine "catch all"-Bequemlichkeitsmethode, die Sie verwenden können, um jeden String mit jedem Parser-Typ zu analysieren: isParsable(Object parser, String str)
. Der Parser kann ein Class
oder ein object
. Dies ermöglicht Ihnen auch, benutzerdefinierte Parser zu verwenden, die Sie geschrieben haben, und sollte für jedes Szenario funktionieren, z. B.:
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");
Hier ist mein Code mit den Methodenbeschreibungen.
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;
}
}
Ein leistungsfähiger Ansatz, der try-catch vermeidet und mit negativen Zahlen und wissenschaftlicher Notation umgeht.
Pattern PATTERN = Pattern.compile( "^(-?0|-?[1-9]\\d*)(\\.\\d+)?(E\\d+)?$" );
public static boolean isNumeric( String value )
{
return value != null && PATTERN.matcher( value ).matches();
}
CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.
42 Stimmen
Alle Lösungen, die mit regulären Ausdrücken vorgeschlagen werden, funktionieren nicht für hexadezimale Zahlen.
0 Stimmen
Und die Übergabe einer Null-Zeichenkette in der Funktion matches(...) führt zur Ausnahme NullPointer.
0 Stimmen
In der Antwort von Max Malysh finden Sie eine prägnante Java 8-Lösung ohne Bibliotheken von Drittanbietern.
0 Stimmen
@HiteshSahu Null-Strings scheinen in der neuesten Version (einschließlich Java 6.x und 7.x) ordnungsgemäß behandelt zu werden.
0 Stimmen
Alle vorgeschlagenen Lösungen zur Verwendung
Integer.parseInt()
nicht in der Lage, Handynummern zu analysieren, dieNumberFormatException
.0 Stimmen
@OscarCastiblanco Alle Zeichenketten sind Zahlen in einer bestimmten Basis.