简体   繁体   中英

Groovy regex with hyphen isn't matching

I want to write a regex that will match any time the substring "my-app" is encountered inside any given string.

I have the following Groovy code:

String regex = ".*my-app*"
String str = getStringFromUserInput()
if(str.matches(regex) {
    println "Match!"
} else {
    println "Doesn't match..."
}

When getStringFromUserInput() returns a string like " blahmy-appfizz ", the code above still reports Doesn't match... . So I figured that hyphens must be a special character in regexes and tried changing the regex to:

String regex = ".*my--app*"

But still nothing has changed. Any ideas as to where I'm going wrong?

The hyphen is no special character.

matches validates the entire input. Try:

String regex = ".*my-app.*"

Note that p* matches zero or more p 's and p.* matches a p followed by zero or more chars (other than line breaks).

Assuming getStringFromUserInput() does not leave any line break char in the input. In which case you'd need to do a trim() to get rid of it, since the .* does not match line break chars.

String.contains seems like a simpler solution than a regex, eg

String stringFromUser = 'my-app'
assert 'foomy-appfoo'.contains(stringFromUser)
assert !'foo'.contains(stringFromUser)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM