我想构造一个正则表达式,匹配 '
或 "
然后匹配其他字符,以 '
或 "
分别匹配,具体取决于开始时遇到的情况。所以这个问题看起来很简单,可以在最后使用反向引用来解决;下面是一些正则表达式代码(它是在 Java 中,所以请注意额外的转义字符,例如 "
之前的 \
):
private static String seekerTwo = "(['\"])([a-zA-Z])([a-zA-Z0-9():;/`\\=\\.\\,\\- ]+)(\\1)";
此代码将成功处理诸如以下的事情:
"hello my name is bob"
'i live in bethnal green'
当我有这样一个字符串时,麻烦就来了:
"hello this seat 'may be taken' already"
在遇到 '
时使用上面的正则表达式将在初始部分失败,然后它将继续并成功匹配 'may be taken'
...但这是显然不够,我需要匹配整个String。
我在想的是,我需要一种方法来忽略在第一组中不匹配的引号类型,方法是将其作为字符包含在第三组的字符集中。但是,我知道没有办法做到这一点。是否有某种偷偷摸摸的 NOT 反向引用函数之类的?我可以用来引用第一组中不匹配的字符的东西?或者以其他方式解决我的困境?
最佳答案
这可以使用负数 lookahead assertions 来完成.以下解决方案甚至考虑到您可以在字符串中转义引号:
(["'])(?:\\.|(?!\1).)*\1
解释:
(["']) # Match and remember a quote.
(?: # Either match...
\\. # an escaped character
| # or
(?!\1) # (unless that character is identical to the quote character in \1)
. # any character
)* # any number of times.
\1 # Match the corresponding quote.
这正确匹配 "hello this seat 'may be taken' already"
或 "hello this seat\"may be taken\"already"
。
在 Java 中,所有反斜杠:
Pattern regex = Pattern.compile(
"([\"']) # Match and remember a quote.\n" +
"(?: # Either match...\n" +
" \\\\. # an escaped character\n" +
"| # or\n" +
" (?!\\1) # (unless that character is identical to the matched quote char)\n" +
" . # any character\n" +
")* # any number of times.\n" +
"\\1 # Match the corresponding quote",
Pattern.COMMENTS);
关于java - 正则表达式;反向引用字符集中不匹配的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9718393/