簡體   English   中英

不匹配 Java 正則表達式

[英]No match for Java Regular Expression

我遇到了一個問題,我的代碼無法找到正則表達式。 代碼:

String content = "This\ is\ an\ example.=This is an example\nThis\ is\ second\:=This is second"
String regex = "\"^.*(?=\\=)\"gm";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(content);
List<String> mKeys = new ArrayList<>();
while (m.find()) {
   mKeys.add(m.group());
}

mKeys 原來是空的。 我已經在這里驗證了我的正則表達式https://regex101.com/r/YResRc/3 我希望列表包含內容中的兩個鍵。

您的內容不包含"引號,也沒有文本gm ,那么您為什么希望正則表達式匹配?

僅供參考:"foo"gm/foo/gm這樣的語法是其他語言為正則表達式文本所做的事情。 Java 不會這樣做。

g標志暗示您使用的是find()循環,而m是影響^$MULTILINE標志,您可以使用(?m)模式指定它,或通過向compile() ,即以下方式之一:

Pattern p = Pattern.compile("foo", Pattern.MULTILINE);

Pattern p = Pattern.compile("(?m)foo");

您的正則表達式應該只是:

(?m)^.*(?==)

這意味着:匹配從一行開始到行上最后一個=符號的所有內容。

測試

String content = "This is an example.=This is an example\nThis is second:=This is second";
String regex = "(?m)^.*(?==)";
Matcher m = Pattern.compile(regex).matcher(content);
List<String> mKeys = new ArrayList<>();
while (m.find()) {
   mKeys.add(m.group());
}
System.out.println(mKeys);

輸出

[This is an example., This is second:]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM