Java Regex,空字符串匹配

时间:2015-07-09 01:55:35

标签: java regex string

我在Java中编写了一个正则表达式来匹配包含如下字符串的句子:

String regex = "((^|([.!?:] ))" + "[^!.?:]*?" + queryStr + ".*?" + "([!.?])|$)+?";

然后我使用正则表达式匹配我的字符串,见下文:

Pattern pattern = Pattern.compile(regex);
String content = "Hello World!!!";
Matcher match = pattern.matcher(content);
int index = 0;
while(match.find(index))
{
   index = match.end() -1;
   System.out.println(match.group());
}

但我怀疑循环永远不会结束,因为正则表达式匹配空字符串。显然,我的正则表达式包括String queryStr。所以,我对此很困惑。任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

你的正则表达式看起来像

((^|([.!?:] ))[^!.?:]*?Hello.*?([!.?])|$)+?

它包含两个选择:

  1. (^|([.!?:] ))[^!.?:]*?Hello.*?([!.?])
  2. $
  3. 所以,问题是你在循环中一直匹配字符串的结尾。

    进行此更改:

    String regex = "(^|[.!?:] )" + "[^!.?:]*?" + queryStr + ".*?" + "([!.?]+?|$)";
    

    现在,它看起来像

    (^|[.!?:] )[^!.?:]*?Hello.*?([!.?]+?|$)
    

    $只会替代[!.?]+?

    enter image description here

    请参阅demo on regex101.com

答案 1 :(得分:0)

正则表达式的每个术语都是可选的。

要防止匹配空白输入,请将其添加到正则表达式的前面:

(?!$)

这是一个向前看,断言当前位置后面没有输入结束(即"某些"正在跟随)