[英]Regex for matching a string literal in Java?
I have an array of regular expressions strings. 我有一组正则表达式字符串。 One of them must match any strings found in a given java file.
其中一个必须匹配给定java文件中找到的任何字符串。
This is the regex string I have so far: "(\\").*[^\\"].*(\\")"
这是我到目前为止的正则表达式字符串:
"(\\").*[^\\"].*(\\")"
However, the string "Hello\\"good day"
is rejected even though the quotation mark inside the string is escaped. I think what I have immediately rejects the string literal when it finds a quotation mark inside regardless of whether it is escaped or not. I need it to accept string literals with escaped quotes but it should reject "Hello"Good day"
. 但是,即使字符串中的引号被转义,字符串
"Hello\\"good day"
也会被拒绝。我认为当我在内部找到引号时,无论是否转义,我都会立即拒绝字符串文字。我需要它接受带有转义引号的字符串文字,但它应该拒绝"Hello"Good day"
。
Pattern regex = Pattern.compile("(\").*[^\"].*(\")", Pattern.DOTALL);
Matcher matcher = regex.matcher("Hello\"good day");
matcher.find(0); //false
In Java you can use this regex to match all escaped quotes between "
and "
: 在Java中,您可以使用此正则表达式匹配
"
和"
之间的所有转义引号:
boolean valid = input.matches("\"[^\"\\\\]*(\\\\.[^\"\\\\]*)*\"");
Regex being used is: 正在使用的正则表达式是:
^"[^"\\]*(\\.[^"\\]*)*"$
Breakup: 分手:
^ # 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.