简体   繁体   English

带连字符的Groovy正则表达式不匹配

[英]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. 我想编写一个正则表达式,该表达式将在任何给定字符串中遇到子字符串“ my-app”的任何时间匹配。

I have the following Groovy code: 我有以下Groovy代码:

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... . getStringFromUserInput()返回类似“ blahmy-appfizz ”的字符串时,上面的代码仍报告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. matches验证整个输入。 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). 请注意, p*匹配零个或多个p ,而p.*匹配p后跟零个或多个char(换行符除外)。

Assuming getStringFromUserInput() does not leave any line break char in the input. 假设getStringFromUserInput()在输入中不保留任何换行符。 In which case you'd need to do a trim() to get rid of it, since the .* does not match line break chars. 在这种情况下,您需要执行trim()来摆脱它,因为.*与换行符不匹配。

String.contains seems like a simpler solution than a regex, eg 与正则表达式相比, String.contains似乎是一个更简单的解决方案,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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