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?
How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.
A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison.
replaceAll() is a function in groovy that replaces all occurrences of a string with a specified string.
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/, "")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With