java - Regular expression on a string -
i have string below
string phone = (123) 456-7890
now program verify if input same pattern string 'phone'
i did following
if(phone.contains("([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]")) { //display pass } else { //display fail }
it didn't work. tried other combinations too. nothing worked.
question : 1. how can achieve without using 'pattern' above? 2. how pattern. tried pattern below
pattern pattern = pattern.compile("(\d+)"); matcher match = pattern.matcher(phone);
if (match.find()) { //displaypass }
string#matches
checks if string matches pattern:
if (phone.matches("\\(\\d{3}\\) \\d{3}-\\d{4}")) { //displaypass }
the pattern regular expression. therefor had escape round brackets, have special meaning in regex (they denote capturing groups).
contains()
checks if string contains substring passed it.
Comments
Post a Comment