java.util.Scanner is a simple text parser. It breaks input into tokens that you request. It can help you with: primitive types (boolean, byte, double, float, int, long, short), and strings that match regular expressions. This function is also available on Android Java.
Example:
Scanner s = new Scanner("CAFE false");
System.out.println(s.nextInt(16));
System.out.println(s.nextBoolean());
Prints
51966
false
You can also work with regular expressions using String.matches(). s.matches(“regex”) returns true if the entire string matches the expression. s.split(“regex”) returns an array of substrings divided at “regex” (the character(s) matching “regex” are not included).
Example
String s = "The food is in the barn."; Boolean b; b = s.matches("foo.*bar"); // false b = s.matches("The.*barn."); // true
You can also work with regular expressions using the java.util.regex package. You use java.util.regex.Pattern() to set the regular expression to match. You use the returned Matcher to test matches and perform other related operations.
You should be aware of the worst-case complexity of their expression. Some can be exponential and lead to a DoS vulnerability.
String s = "The food is in the barn.";
Pattern p = Pattern.compile("foo.*bar");
Matcher m = p.matcher(s);
b = m.matches(); // false
b = Pattern.compile("The.*barn.").matcher(s).matches(); // true
b = Pattern.matches("The.*barn.",s); // true