我有一个正则表达式字符串数组。其中之一必须匹配在给定 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
RegEx Demo
关于java - 用于匹配 Java 中的字符串文字的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37032620/