2014-09-06 94 views
2

提取字符串的樣本源代碼以匹配是正則表達式來從Java代碼

String string="welcome"; 
String k="a\"welcome"; 

我使用在Java "(\"[^(\")]*\")"正則表達式。

但這提取

0:"welcome" 
0:"a\" 

預計產量

0:"welcome" 
0:"a\"welcome" 

我應該在正則表達式什麼變化,以獲得預期的輸出?

Java源:

private static String pattern1="(\"[^(\")]*\")"; 
public void getStrings(){ 
    Pattern r = Pattern.compile(pattern1); 
    Matcher m = r.matcher("String string=\"welcome\";\n" + 
      "String k=\"a\\\"welcome\";"); 


    while(m.find()){ 
     System.out.println("0:"+m.group(0)); 
    } 
} 
+0

你應該告訴我們什麼樣的模式不匹配,或者更好的匹配原則是什麼。 – Tony 2014-09-06 14:07:26

回答

1

只需使用前瞻和回顧後您的正則表達式,,

(?<==)(".*?")(?=;) 

獲得來自組索引1

DEMO

Pattern r = Pattern.compile("(?<==)(\".*?\")(?=;)"); 
Matcher m = r.matcher("String string=\"welcome\";\n" + 
      "String k=\"a\\\"welcome\";"); 
while(m.find()){ 
     System.out.println("0:"+m.group(1)); 
} 

輸出:

0:"welcome" 
0:"a\"welcome" 

OR

使用的*貪婪,

Pattern r = Pattern.compile("(\".*\")"); 

OR

它會跳過這是由一個反斜槓雙引號,

Pattern r = Pattern.compile("(\\\".*?(?<=[^\\\\])\\\")"); 
+0

你也可以嘗試這個http://regex101.com/r/vN2vU4/4。它只是跳過雙引號,後面是反斜槓。 – 2014-09-06 14:28:08

+0

或這個,'(\「。*?[^ \\] \」)' – 2014-09-06 14:33:31

0

爲什麼你甚至不打擾變量賦值。你知道""中的所有內容都是一個字符串。

"(.+)"\s*;應該做得很好。