Simple Groovy replace using regex

I recognize two errors in your code. First one is probably a typo: you are not surrounding the phone number with quotation marks so it's an integer: 1 + 555 - 555 - 5555 = -5554

Also, you should use replaceFirst since there's no method replace in String taking a Pattern as first parameter. This works:

def mphone = "1+555-555-5555"
result = mphone.replaceFirst(/^1/, "")

replace is a java Method of Java's String, which replace a character with another:

assert "1+555-551-5551".replace('1', ' ') == " +555-55 -555 "

What you are looking for is replaceAll, which would replace all occurrences of a regex, or replaceFirst, that would replace the first occurrence only:

assert "1+555-551-5551".replaceAll(/1/, "") == "+555-55-555"
assert "1+555-551-5551".replaceFirst(/1/, "") == "+555-551-5551"

The ^ in your regex means that the one must be at the beginning:

assert "1+555-551-5551".replaceAll(/^1/, "") == "+555-551-5551"

so the code you posted was almost correct.

Tags:

Groovy

Regex