2014-07-11 23 views
-3

我是新來java編碼和使用模式匹配。我正在從文件中讀取此字符串。所以,這會導致編譯錯誤。我有一個字符串如下:使用正則表達式的Java模式匹配

String str = "find(\"128.210.16.48\",\"Hello Everyone\")" ; // no compile error 

我想從上面的字符串中提取「128.210.16.48」值和「Hello Everyone」。這個值不是恆定的。

你能給我一些建議嗎? 感謝

+1

是可編譯的嗎? – Braj

+2

不是有效的字符串文字。 – Henry

+0

描述你的可能值,以便我們可以理解模式。例如,你是否期望無效的IP地址,如果你這樣做,他們的命運應該是什麼? –

回答

2

嘗試用String.split()

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],再次用字母(")分割字符串,然後從數組中選擇第二個元素。第二個字符串也完成了。

+0

謝謝。它工作! – user2737926

+0

你能給我解釋嗎?這樣我就可以理解分裂的工作。 – user2737926

+0

非常感謝! – user2737926

3

我建議你使用String#split()方法,但仍,如果你正在尋找的正則表達式,然後嘗試從索引1

("[^"][\d\.]+"|"[^)]*+) 

Online demo

示例代碼獲得匹配的組:

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 
+0

也這個工具可能有幫助,但它不是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

1

接受的答案是好的,但如果由於某種原因,你想仍使用正則表達式(或任何人發現這個問題),而不是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 

注:這將ONL如果"僅用作分隔符,則y工作。以here爲例,以Braj's演示爲例。

+0

如果字符串也包含''',這將不起作用。[demo](http://regex101.com/r/eV5aP3/5) – Braj

+0

True,我會將這個警告編輯到我的答案中,謝謝! –