I have this regex which is used to validate phone numbers.
^\\(?(\\d{2,3})\\)?[-(). ]?(\\d{2,3})[-(). ]?(\\d{4})$
(Yes, I know it is not perfect, but I don't really care). I am just using it to replace phone numbers with another string, say ### to remove sensitive information. So false positives are fine.
It works when the string I am searching is only a phone number. This works:
String PHONE_PATTERN = "^\\(?(\\d{2,3})\\)?[-(). ]?(\\d{2,3})[-(). ]?(\\d{4})$";
String phone = "123-123-1234";
System.out.println(s.replaceAll(PHONE_PATTERN, "###")); //prints '###'
But with surrounding text it does not work:
String PHONE_PATTERN = "^\\(?(\\d{2,3})\\)?[-(). ]?(\\d{2,3})[-(). ]?(\\d{4})$";
String phone = "some other text 123-123-1234";
System.out.println(s.replaceAll(PHONE_PATTERN, "###"));
By does not work, I mean the text is printed unchanged.
What do I need to change on my regex to get this to work so that the second example prints
some other text ###




^and&automatically when building your regex? When I write a regex, I have to actively think about whether either of them should be there, like "Do I only need to match this at the beginning of strings/lines?"