Can anyone let me know the meaning of below regular expression patterns?
Pattern p1=Pattern.compile("^1?(\\d{10})");
Pattern p2=Pattern.compile("^1?([1-9])(\\d{9})");
Off the top of my head, these look like regular expressions to match US phone numbers.
The first one matches a number comprised of either 10 digits, or 11 digits if the first number is 1.
1?
— optionally match a 1\d
— match a digit between 0 and 9 (escaped as \\d
in Java){10}
— match the preceding character 10 times (in this case, a digit)The second one matches the same pattern, with the exception that the first (or second, if 1 is present) digit cannot be a 0.
1?
— optionally match a 1[1-9]
— match a single digit between 1 and 9\d
— match a digit between 0 and 9 (escaped as \\d
in Java){9}
— match the preceding character 9 times (in this case, a digit)Note that both expressions begin with ^
, which simply means "match only at the start of the line". Also note that parentheses, as used here, are used for capturing groups of characters, but do not affect the meaning of the expression.
For explaining regex, you can always use this online explainer
The output for your regexes:
Regex: ^1?(\d{10}) NODE EXPLANATION -------------------------------------------------------------------------------- ^ the beginning of the string -------------------------------------------------------------------------------- 1? '1' (optional (matching the most amount possible)) -------------------------------------------------------------------------------- ( group and capture to \1: -------------------------------------------------------------------------------- \d{10} digits (0-9) (10 times) -------------------------------------------------------------------------------- ) end of \1
Regex: ^1?([1-9])(\d{9}) NODE EXPLANATION -------------------------------------------------------------------------------- ^ the beginning of the string -------------------------------------------------------------------------------- 1? '1' (optional (matching the most amount possible)) -------------------------------------------------------------------------------- ( group and capture to \1: -------------------------------------------------------------------------------- [1-9] any character of: '1' to '9' -------------------------------------------------------------------------------- ) end of \1 -------------------------------------------------------------------------------- ( group and capture to \2: -------------------------------------------------------------------------------- \d{9} digits (0-9) (9 times) -------------------------------------------------------------------------------- ) end of \2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With