String s = "test";
Pattern pattern = Pattern.compile("\\n((\\w+\\s*[^\\n]){0,2})(\\b" + s + "\\b\\s)((\\w+\\s*){0,2})\\n?");
Matcher matcher = pattern.matcher(searchableText);
boolean topicTitleFound = matcher.find();
startIndex = 0;
while (topicTitleFound) {
int i = searchableText.indexOf(matcher.group(0));
if (i > startIndex) {
builder.append(documentText.substring(startIndex, i - 1));
...
这是我所理解的文字:
Some text comes here
topicTitle test :
test1 : testing123
test2 : testing456
test3 : testing789
test4 : testing9097
当我在 http://regexpal.com/ 或 http://www.regexplanet.com 上测试这个正则表达式时,我清楚地发现标题是:“topicTitle test”。但在我的 java 代码中 topicTitleFound 返回 false。
请帮忙
最佳答案
searchableText< 中的换行符 (
。这将导致匹配在行边界处失败。'\n'
) 之前可能有回车符 ('\r'
)/
为了使您的多线模式更加强大,请尝试使用 MULTILINE编译正则表达式时的选项。然后根据需要使用 ^
和 $
来匹配行边界。
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
<小时/>
更新:
实际测试您的代码后,我发现无论回车符是否存在,该模式都匹配。换句话说,您的代码按原样“工作”,并且首次分配时(在 while
循环之外),topicTitleFound
为 true
。
您确定 topicTitleFound
的结果为 false
吗?或者问题出在循环中?
顺便说一句,使用 indexOf()
既浪费又尴尬,因为匹配器已经存储了组 0 开始的索引。改用这个:
int i = matcher.start(0);
关于java - Matcher.Find() 在应该为 true 时返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5637377/