Howes
Howes

Reputation: 819

Simple Groovy replace using regex

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?

Upvotes: 50

Views: 123201

Answers (2)

Esteban
Esteban

Reputation: 2579

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/, "")

Upvotes: 72

Antoine
Antoine

Reputation: 5198

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.

Upvotes: 44

Related Questions