[英]Regex for matching a string literal in 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
在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.