我正在尋找一種方法來檢查多行字符串(來自pdf)是否包含一定不能以特定前綴開頭的特定字母組合。具體來說,我正在嘗試查找包含ARC但不包含的字符串NON-ARC。我發(fā)現(xiàn)了這個很好的示例正則表達(dá)式,用于不以序列開頭的字符串,但它似乎不適用于我的問題。使用我的模式^(?!NON\\-)ARC.*,我在單行測試中得到了預(yù)期的結(jié)果,在實際輸入的情況下,否定前瞻斷言有誤報。這是我所做的:@Testpublic void testRegexLookAhead() { String strTestSimplePos = "ARC 0.1-1"; String strTestSimpleNeg = "NON-ARC 3.4-1"; String strTestRealPos = "HEADLINE\r\n" + "Subheader Author\r\n" + "ARC 0.1-1\r\n" + "20190211"; String strTestRealNeg = "HEADLINE\r\n" + "Subheader Author\r\n" + "NON-ARC 0.1-1\r\n" + "20190211"; //based on https://stackoverflow.com/questions/899422/regular-expression-for-a-string-that-does-not-start-with-a-sequence String regexNoNON = "^(?!NON\\-)ARC.*"; Pattern noNONPatter = Pattern.compile(regexNoNON); System.out.println(noNONPatter.matcher(strTestSimplePos).find()); //true OK System.out.println(noNONPatter.matcher(strTestSimpleNeg).find()); //false OK System.out.println(noNONPatter.matcher(strTestRealPos).find()); //false but should be true -> does not work as intended System.out.println(noNONPatter.matcher(strTestRealNeg).find()); //false OK 如果有人能指出出了什么問題,我會很高興...編輯:這被標(biāo)記為How to use java regex to match a line - 但是我根本沒有嘗試使用 regex 來匹配行。只需要一種方法來為多行文本輸入找到特定序列(帶有負(fù)前瞻)。解決另一個問題的一種方法也是解決這個問題的方法(使用 java.util.regex.Pattern.MULTILINE 編譯模式) - 但問題充其量是相關(guān)的。
多行文本的負(fù)前瞻斷言
慕無忌1623718
2022-06-15 09:38:14