Home > OS >  How to match this string in Regex pattern?
How to match this string in Regex pattern?

Time:10-20

I have a string where this string phonenumber={9 digits or 0 digits, just this two options} is repeated multiple times, what I want to do is get a regex pattern to match this string and replace it for an empty string.

I tried this but it didn't work, I don't know if the problem is the pattern or the way I'm trying to replace all of "phonenumber={9 digits}" from the base string:

var result =baseString.toString().lowercase().replace(Regex("\\\\bphonenumber=\\\\b\\d{9}"),"")

CodePudding user response:

There are these issues with that regex:

  • The regex will see \\b instead of \b, so in the string literal you need to add only one level of escaping: "\\b". Alternatively, use the raw string literal (with """ delimiters), and then there is no escaping.
  • The second \b occurs at a spot where it is not needed, since it sits between = and a digit. You'll want this \b to be put after the digits pattern.
  • There is no provision to match when there are 0 digits. For this you can make the 9 digits optional with a ?

So:

Regex("""\bphonenumber=(?:\d{9}\b)?""")
  • Related