为了简单起见,我们以下面的例子为例:
iphone Foo.bar.StartTimestamp:[2012-11-12 TO 2016-02-15] and apple Bar.Foo.BarTimestamp:[2012-11-12 TO 2016-02-15] apple
从上面的文本中,我想使用正则表达式过滤Foo.bar.StartTimestamp:[2012-11-12 TO 2016-02-15]
和Bar.Foo.BarTimestamp:[2012-11-12 TO 2016-02-15]
。可以有任何组合来代替Bar.Foo.BarTimestamp:[2012-11-12 TO 2016-02-15]
,但它将采用相同的格式。
我试过这个(?<!\\S)[][^[]]*
正则表达式,但它只过滤方括号括起来的文本。
我应该如何构造正则表达式以获得所需的结果?
以下是指向regex101.com的链接:https://www.regex101.com/r/QLP4jB/1
发布于 2016-12-25 07:09:11
试试这个正则表达式:
\w+(\.\w+)*:\[[^]]*\]
发布于 2016-12-25 07:11:13
您可以使用此正则表达式,而无需任何查找:
(?:\w+\.)+\w+:\[[^]]+\]
Java代码
final String regex = "(?:\\w+\\.)+\\w+:\\[[^]]+\\]";
final String string = "iphone Foo.bar.StartTimestamp:[2012-11-12 TO 2016-02-15] and apple Bar.Foo.BarTimestamp:[2012-11-12 TO 2016-02-15] apple";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Matched: " + matcher.group(0));
}
https://stackoverflow.com/questions/41319218
复制