Java regexp,在分隔的字符串中获取字符,忽略其间的文本

时间:2016-01-11 16:25:04

标签: java regex

我有一个字符串,如;

One Two Three|null:Two Two Three|10:Two Three|10:Six Two Three|null

我的正则表达式是:

(^|:)+Two Three(?!\|null)

此模式返回

Two Three|10

但它不会返回

Two Two Three|10

也是。我如何在“:”和“Two Three”之间跳过文本

更新:

 Pattern p = Pattern.compile("(?:^|[: ])+("+searchString+")(?!\\|null)", Pattern.CASE_INSENSITIVE);
 Matcher m = p.matcher("One Two Three|null:Two Two Three|10:Two Three|10:Six Two Three|null");

 System.out.println(m.matches());

返回false

1 个答案:

答案 0 :(得分:1)

您可以将此正则表达式与空格一起用作前面的字符:

(?:^|[: ])((?:Two )+Three)(?!\|null)

在Java中:

String re = "(?:^|[: ])((?:Two )+Three)(?!\\|null)";

与lookbehind相同:

(?<=[: ]|^)(?:Two )+Three(?!\|null)

RegEx Demo

<强>代码:

Pattern p = Pattern.compile("(?:^|[: ])("+searchString+")(?!\\|null)", Pattern.CASE_INSENSITIVE);
 Matcher m = p.matcher("One Two Three|null:Two Two Three|10:Two Three|10:Six Two Three|null");

while(m.find()) {
    System.out.println(m.group(1));
}