2011-08-05 100 views
0

我有一個表達式字符串如下(整行字符串):如何使用正則表達式從表達式字符串中提取* string *?

String s = prefix + "abc\"abc\"abc".toUpperCase(); 

我想使用正則表達式,其理解「後一個雙引號,以提取「ABC \」 ABC \「ABC」反斜槓不是字符串的結尾。「我怎麼做到的?非常感謝你!


FINALLY

是你們給了我一些提示,最後我想通了,並且這是我的Java代碼:

public class RegExpTest { 

    private static final Pattern PATTERN = Pattern.compile("(([^\\\\]|^)\").*?([^\\\\]\")"); 

    public static void main(String[] args) { 
     printStrings("He said \"Hello, \\\"\\\"\\\"\\\"name\\\"\", \"baby\""); 
     printStrings("\"Go away and \\\"never\\\" come back!\" he said."); 
     printStrings("\\\" outer \"inner\""); 
    } 

    private static void printStrings(String string) { 
     System.out.println(string); 
     System.out.println(extractStrings(string)); 
     System.out.println(); 
    } 

    private static List<String> extractStrings(String string) { 
     Matcher matcher = PATTERN.matcher(string); 
     List<String> resultList = new ArrayList<String>(); 

     while (matcher.find()) { 
      String group = matcher.group(); 
      if (!group.startsWith("\"")) { 
       group = group.substring(1); // remove first non-double-quoter 
      } 
      resultList.add(group); 
     } 
     return resultList; 
    } 
} 

它的輸出如下:

He said "Hello, \"\"\"\"name\"", "baby" 
["Hello, \"\"\"\"name\"", "baby"] 

"Go away and \"never\" come back!" he said. 
["Go away and \"never\" come back!"] 

\" outer "inner" 
["inner"] 

謝謝大家。

回答

0

你可以使用:

/".*?[^\]"/ 

第一"之後的所有字符,直到下一個"達到這不是由\之前。

請注意,這也不會匹配""。由於引號之間必須至少有一個字符才能匹配。

0
"((?:\\"|[^"])+)" 

將匹配\」第一,那麼任何非引號的字符串。組(1)內部串。

0

我試圖@ PaulPRO在拉德軟件的表達設計師的答案,但它沒有工作的你的字符串對我來說,這對你的輸入使用上面提到的工具起作用

\".+?(\\|\"){1} 
相關問題