Regular expression in java for validating numbers
Capturing groups and Backreferences can be confusing, so let’s understand this with an example.
println(Pattern.matches("(\w\d)\1", "a2a2")); //true println(Pattern.matches("(\w\d)\1", "a2b2")); //false println(Pattern.matches("(AB)(B\d)\2\1", "ABB2B2AB")); //true println(Pattern.matches("(AB)(B\d)\2\1", "ABB2B3AB")); //false In the first example, at runtime first capturing group is (\w\d) which evaluates to “a2” when matched with the input String “a2a2” and saved in memory.
This regex will tolerate the form XXX XXX XXX, XXXXXXXX or XXX-XXX-XXX. Since every part of a path is separated by a \ character, we only need to find the last one.
Note that there's just no way to check if the last portion of a path is a file or a directory just by the name alone.
A regular expression is not language specific but they differ slightly for each language. Note that the pattern defined by regex is applied on the String from left to right and once a source character is used in a match, it can’t be reused.
Regular Expression in Java is most similar to Perl. For example, regex “121” will match “31212142121” only twice as “_121____121”.
Your user interface should take care of the formatting problem by having a clear documentation on the format and/or split the phone into parts (area, exchange, number) and/or have an entry mask.
The following expression is pretty lenient on the format and should accept 999-999-9999, 9999999999, (999) 999-9999.
Regular Expression can be used to search, edit or manipulate text. You should use Pattern and Matches classes only when you need to manipulate the input String or you need to reuse the pattern.Thanks to the international phone numbering plan (ITU-T E.164), phone numbers cannot contain more than 15 digits. The significance of this is that EPP-style international phone numbers are increasingly used and recognized, and therefore provide a good alternative format for storing (and validating) international phone numbers.