Java 如何检查字符串是否与 Groovy 中的模式匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28467956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:18:03  来源:igfitidea点击:

How to check if a String matches a pattern in Groovy

javagroovy

提问by kicks

How do I check if a string matches a pattern in groovy? My pattern is "somedata:somedata:somedata", and I want to check if this string format is followed. Basically, the colon is the separator.

如何检查字符串是否与 groovy 中的模式匹配?我的模式是“somedata:somedata:somedata”,我想检查是否遵循此字符串格式。基本上,冒号是分隔符。

回答by cangoektas

Try using a regular expression like .+:.+:.+.

尝试使用像.+:.+:.+.

import java.util.regex.Matcher
import java.util.regex.Pattern

def match = "somedata:somedata:somedata" ==~ /.+:.+:.+/

回答by Nick Grealy

Groovy regular expressions have a ==~operator which will determine if your string matches a given regular expression pattern.

Groovy 正则表达式有一个==~运算符,它将确定您的字符串是否与给定的正则表达式模式匹配。

Example

例子

// ==~ tests, if String matches the pattern
assert "2009" ==~ /\d+/  // returns TRUE
assert "holla" ==~ /\d+/ // returns FALSE

Using this, you could create a regex matcher for your sample data like so:

使用它,您可以为您的示例数据创建一个正则表达式匹配器,如下所示:

// match 'somedata', followed by 0-N instances of ':somedata'...
String regex = /^somedata(:somedata)*$/

// assert matches...
assert "somedata" ==~ regex
assert "somedata:somedata" ==~ regex
assert "somedata:somedata:somedata" ==~ regex

// assert not matches...
assert "somedata:xxxxxx:somedata" !=~ regex
assert "somedata;somedata;somedata" !=~ regex

Read more about it here:

在此处阅读更多相关信息:

http://docs.groovy-lang.org/latest/html/documentation/#_match_operator

http://docs.groovy-lang.org/latest/html/documentation/#_match_operator

回答by kicks

Was able to resolve this using:

能够使用以下方法解决此问题:

myString.matches("\S+:\S+:\S+")

myString.matches("\S+:\S+:\S+")

回答by TCH

The negate regex match in Groovy should be

Groovy 中的否定正则表达式匹配应该是

 String regex = /^somedata(:somedata)*$/   
 assert !('somedata;somedata;somedata' ==~ regex)  // assert success!