Simple Groovy replace using regex
Solution 1
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/, "")
Solution 2
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.
Related videos on Youtube

Howes
Updated on July 09, 2022Comments
-
Howes 11 months
I've been reading through regex and I thought this would work but it doesn't seem to want to work. All I need to do is strip the leading 1 off a phone number if it exists.
So:
def mphone = 1+555-555-5555 mphone.replace(/^1/, "")
Shouldn't this output +555-555-5555?
-
Antoine about 11 yearsYou meant
def mphone = "1+555-555-5555"
(with quotes)
-
-
Johnathon Sanders about 11 yearsGood answer. One caveat, don't forget Strings are immutable. Make sure to reassign mphone:
mphone = mphone.replaceFirst(/^1/, "")
-
Esteban about 11 years@Johnathon great comment, using the last line as a return value would do but I didn't think it could also be a mistaken in-place replacement
-
Ashok Koyi over 10 yearsString contains replace(CharSequence, CharSequence) method