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 methodsfor (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 methodcontinue; // 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;}}
var re = new RegExp("^-?\d+([,\.]\d+)?([eE]-?\d+)?$");re.test("-6546"); // truere.test("-6546355e-4456"); // truere.test("-6546.355e-4456"); // true, though debatablere.test("-6546.35.5e-4456"); // falsere.test("-6546.35.5e-4456.6"); // false
Pattern PATTERN = Pattern.compile( "^(-?0|-?[1-9]\\d*)(\\.\\d+)?(E\\d+)?$" );
public static boolean isNumeric( String value ){return value != null && PATTERN.matcher( value ).matches();}
static boolean isNumber(String s) {final int len = s.length();if (len == 0) {return false;}int dotCount = 0;for (int i = 0; i < len; i++) {char c = s.charAt(i);if (c < '0' || c > '9') {if (i == len - 1) {//last character must be digitreturn false;} else if (c == '.') {if (++dotCount > 1) {return false;}} else if (i != 0 || c != '+' && c != '-') {//+ or - allowed at startreturn false;}
}}return true;}
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 signArray 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
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;}
String number = "132452";if(number.matches("([0-9]{6})"))System.out.println("6 digits number identified");
检查之间的可变长度数(假设长度为4到6)
// {n,m} n <= length <= mString 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");
检查可变长度十进制数之间(假设4到7长度)
// It will not count the '.' (Period) in lengthString 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");
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 pointSystem.out.println(str);
return str.replaceAll("[0-9]","").length() == 0;}
public static boolean isNumeric(final String input) {//Check for null or blank stringif(input == null || input.isBlank()) return false;
//Retrieve the minus sign and decimal separator characters from the current Localefinal var localeMinusSign = DecimalFormatSymbols.getInstance().getMinusSign();final var localeDecimalSeparator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
//Check if first character is a minus signfinal var isNegative = input.charAt(0) == localeMinusSign;//Check if string is not just a minus signif (isNegative && input.length() == 1) return false;
var isDecimalSeparatorFound = false;
//If the string has a minus sign ignore the first characterfinal 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 separatorfor (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;}