[英]Matcher.Find() returns false when it should be true
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));
...
這是我說的文字:
一些文字來了
topicTitle測試:
test1:測試123
test2:測試456
test3:測試789
test4:testing9097
當我在http://regexpal.com/或http://www.regexplanet.com上測試此正則表達式時,我清楚地找到了標題:“ topicTitle測試”。 但是在我的Java代碼topicTitleFound中返回false。
請幫忙
可能是在searchableText
的換行符( '\\n'
)之前有回車符( '\\r'
)。 這將導致匹配在行邊界處失敗。
為了使多行模式更健壯,請在編譯正則表達式時嘗試使用MULTILINE選項。 然后根據需要使用^
和$
匹配線邊界。
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
更新:
在實際測試完您的代碼之后,我發現該模式與是否存在回車符相匹配。 換句話說,您的代碼“按原樣”運行,並且當首次分配topicTitleFound
時(在while
循環之外),它為true
。
您確定對topicTitleFound
是false
的嗎? 還是問題出在循環中?
順便說一句,由於匹配器已經存儲了從第0組開始的索引,因此indexOf()
的使用非常浪費且笨拙。 使用此代替:
int i = matcher.start(0);
您的正則表達式很難解密-並不是很明顯您要執行的操作。 我想到的一件事是,您的正則表達式期望匹配以換行符開頭,而示例文本則不然。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.