Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Groovy replace using regex

Tags:

regex

groovy

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?

like image 627
Howes Avatar asked Mar 20 '12 14:03

Howes


People also ask

Can I use regex in replace?

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.

How do you write regex in groovy?

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.

How do I replace a character in groovy?

replaceAll() is a function in groovy that replaces all occurrences of a string with a specified string.


1 Answers

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/, "") 
like image 145
Esteban Avatar answered Sep 22 '22 11:09

Esteban