Pattern.comple null语法异常



模式行不断抛出空指针,我不知道为什么。我尝试了Pattern.quote,但结果是:

Pattern p: Q.*(bread){1, 1}.{1, 1}(bread){1, 1}.*E|java.util.regex.Matcher[pattern=Q.*(bread){1, 1}.{1, 1}(bread){1, 1}.*E region=0,13 lastmatch=]

这完全不是应该的。我想返回两个bread子字符串之间的字符串。

public String getSandwich(String str) {
  Pattern p = Pattern.compile(".*(bread){1, 1}(.{1, 1})(bread){1, 1}.*");
  Matcher m = p.matcher(str);
  if (m.find()) {
      return m.group(2);
  } else {
  return "";
  }
}

有什么想法吗?

您的模式中存在语法错误:

.*(bread){1, 1}(.{1, 1})(bread){1, 1}.*
no space ---^ here -^ and here ---^

顺便说一句,让一个量词像{1,1}一样表达有什么意义?

此处测试:http://fiddle.re/y2mxd6

最新更新