我是新來java編碼和使用模式匹配。我正在從文件中讀取此字符串。所以,這會導致編譯錯誤。我有一個字符串如下:使用正則表達式的Java模式匹配
String str = "find(\"128.210.16.48\",\"Hello Everyone\")" ; // no compile error
我想從上面的字符串中提取「128.210.16.48」值和「Hello Everyone」。這個值不是恆定的。
你能給我一些建議嗎? 感謝
我是新來java編碼和使用模式匹配。我正在從文件中讀取此字符串。所以,這會導致編譯錯誤。我有一個字符串如下:使用正則表達式的Java模式匹配
String str = "find(\"128.210.16.48\",\"Hello Everyone\")" ; // no compile error
我想從上面的字符串中提取「128.210.16.48」值和「Hello Everyone」。這個值不是恆定的。
你能給我一些建議嗎? 感謝
String str = "find(\"128.210.16.48\",\"Hello Everyone\")" ;
System.out.println(str.split(",")[0].split("\"")[1]);
System.out.println(str.split(",")[1].split("\"")[1]);
輸出:
128.210.16.48
Hello Everyone
編輯: 說明:
對於第一個字符串用逗號分開(,)
它。從該數組中選擇第一個字符串作爲str.split(",")[0]
,再次用字母(")
分割字符串,然後從數組中選擇第二個元素。第二個字符串也完成了。
我建議你使用String#split()
方法,但仍,如果你正在尋找的正則表達式,然後嘗試從索引1
("[^"][\d\.]+"|"[^)]*+)
示例代碼獲得匹配的組:
String str = "find(\"128.210.16.48\",\"Hello Everyone\")";
String regex = "(\"[^\"][\\d\\.]+\"|\"[^)]*+)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
輸出:
"128.210.16.48"
"Hello Everyone"
模式說明:
( group and capture to \1:
" '"'
[^"] any character except: '"'
[\d\.]+ any character of: digits (0-9), '\.' (1
or more times (matching the most amount
possible))
" '"'
| OR
" '"'
[^)]* any character except: ')' (0 or more
times (matching the most amount
possible))
) end of \1
也這個工具可能有幫助,但它不是100%準確http://txt2re.com/index.php3?s=find(\%22128.210.16.48\%22,\%22Hello%20Everyone\%22)&-11&- 52&-70&-48&4&3&-54&-72&-73&-51&-50 – TheBetaProgrammer
接受的答案是好的,但如果由於某種原因,你想仍使用正則表達式(或任何人發現這個問題),而不是String.split這裏的東西:
String str = "find(\"128.210.16.48\",\"Hello Everyone\")" ; // no compile error
String regex1 = "\".+?\"";
Pattern pattern1 = Pattern.compile(regex1);
Matcher matcher1 = pattern1.matcher(str);
while (matcher1.find()){
System.out.println("Matcher 1 found (trimmed): " + matcher1.group().replace("\"",""));
}
輸出:
Matcher 1 found (trimmed): 128.210.16.48
Matcher 1 found (trimmed): Hello Everyone
如果字符串也包含''',這將不起作用。[demo](http://regex101.com/r/eV5aP3/5) – Braj
True,我會將這個警告編輯到我的答案中,謝謝! –
是可編譯的嗎? – Braj
不是有效的字符串文字。 – Henry
描述你的可能值,以便我們可以理解模式。例如,你是否期望無效的IP地址,如果你這樣做,他們的命運應該是什麼? –