ubiquibacon
ubiquibacon

Reputation: 10667

Why isn't this regex working?

Regex works fine here, but my script gets choked up on the underscores when I run it. The underscores should not need to be escaped... What is the deal?

Just trying to grab any leading/trailing $ and _:

def someString1 = "__test"
def someString2 = "$test"
def someString3 = "test_"
def someString4 = "$test_"

//...

    def matcher = someString1 =~ /([\$_]*)(.+?)([\$_]*)/

Using Netbeans as my IDE and the coloring of the regex indicates it thinks the underscores are variables. Same is true if the dollar signs are escaped or not escaped.

enter image description here

Upvotes: 2

Views: 103

Answers (2)

Joel
Joel

Reputation: 4772

This is because the $ is a String and GString placeholder in groovy. Since you are using groovy to do the regex, you will have to escape anything that follows a $ or I am sure its possible hard code the expression in a string..

def matcher = someString =~ /([\$\_]*)(.+?)([\$\_]*)/

Upvotes: 2

Nick
Nick

Reputation: 4362

The express $_ in regex is a back-reference for the entire input string. Try changing your regex to this:

([_\$]*)(.+?)([_\$]*)

Upvotes: 3

Related Questions