2016-05-04 69 views
1

我有一個正則表達式字符串數組。其中一個必須匹配在給定的java文件中找到的任何字符串。正則表達式匹配Java中的字符串文字?

這是正則表達式字符串我到目前爲止:"(\").*[^\"].*(\")"

然而,即使在字符串中的引號被轉義字符串"Hello\"good day"被拒絕。我認爲當我們在裏面找到一個引號時,立即拒絕字符串文字,而不管它是否被轉義。我需要它接受帶有轉義引號的字符串文字,但它應該拒絕"Hello"Good day"

Pattern regex = Pattern.compile("(\").*[^\"].*(\")", Pattern.DOTALL); 
    Matcher matcher = regex.matcher("Hello\"good day"); 
    matcher.find(0); //false 
+1

請發佈[MCVE]。 –

+0

你可能想要在''字符上加一個負面的後視,但是你會很難處理評論。 – aioobe

+0

你也說''你好\'美好的一天'被拒絕'然後你說'但是它應該拒絕「你好」,祝你好日子「'。這意味着它的工作。 – PeterS

回答

6

在Java中,你可以使用這個正則表達式匹配""之間的所有轉義引號:

boolean valid = input.matches("\"[^\"\\\\]*(\\\\.[^\"\\\\]*)*\""); 

使用正則表達式是:

^"[^"\\]*(\\.[^"\\]*)*"$ 

破碎:

^    # line start 
"    # match literal " 
[^"\\]*  # match 0 or more of any char that is not " and \ 
(   # start a group 
    \\   # match a backslash \ 
    .   # match any character after \ 
    [^"\\]* # match 0 or more of any char that is not " and \ 
)*   # group end, and * makes it possible to match 0 or more occurrances 
"    # match literal " 
$    # line end 

RegEx Demo

+0

Pattern regex = Pattern.compile(「 「([\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ *]你好\「美好的一天」); 布爾結果= matcher.find(0); //以這種方式使用正則表達式字符串時,我得到了錯誤信息。我怎麼才能使它工作 – pythonbeginner4556

+1

沒關係,它的工作!謝謝 – pythonbeginner4556

+0

如果使用羣集組而不是捕獲,稍微快一點。 – sln

相關問題