为了简单起见,让我们看下面的例子:
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
最佳答案
您可以使用此正则表达式而无需任何环视:
(?:\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));
}
关于java - 过滤带点并以方括号结尾的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319218/