Simple Groovy replace using regex

97,683

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.

Share:
97,683

Related videos on Youtube

Howes
Author by

Howes

Updated on July 09, 2022

Comments

  • Howes
    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
      Antoine about 11 years
      You meant def mphone = "1+555-555-5555" (with quotes)
  • Johnathon Sanders
    Johnathon Sanders about 11 years
    Good answer. One caveat, don't forget Strings are immutable. Make sure to reassign mphone: mphone = mphone.replaceFirst(/^1/, "")
  • Esteban
    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
    Ashok Koyi over 10 years
    String contains replace(CharSequence, CharSequence) method