1

我正在练习我的正则表达式外观,为此,我试图从 SQL 插入语句中提取表名。我有正则表达式(?<=INSERT INTO )\w+(?= (\(|VALUES).+),我正在 String 上测试它INSERT INTO tests VALUES (regex, test)。虽然我知道我的正则表达式没有精心完成,但我希望它能够匹配tests我输入的子字符串。

String.split我正在使用 Java 的正则表达式引擎,并且正在打印我使用正则表达式和使用正则表达式时发生的结果Pattern.matches。我得到以下看似矛盾的结果

regex> (?<=INSERT INTO )\w+(?= (\(|VALUES).+)
string> INSERT INTO tests VALUES (regex, test)
[INSERT INTO ,  VALUES (regex, test)]
regex> (?<=INSERT INTO )\w+(?= (\(|VALUES).+)
string> INSERT INTO tests VALUES (regex, test)
false

现在只是为了记录下来,产生第一个结果的代码是

Arrays.toString(searchString.split(regex))

而第二个来自

Pattern.matches(regex, searchString)

不是split将匹配项上的字符串拆分为其参数吗?这意味着正则表达式匹配tests,因此结果[INSERT INTO , VALUES (regex, test)]。那么,为什么Pattern.matches返回 false 呢?我错过了什么?

4

2 回答 2

4

如果您使用以下方法遇到同样的问题,我会尝试:

Pattern p = Pattern.compile(yourRegex);
Matcher m = p.matcher(inputString); 

并检查是否m.find()返回 true

Pattern.matches期望整个字符串匹配 - 它可能有环视问题,因为这些是零宽度断言,因此匹配的字符被丢弃。

于 2012-04-28T19:40:31.613 回答
1

Just to add a little bit to Joanna's answer: Lookaheads and lookbehinds don't participate in the match. Pattern.matches requires that the regex match starting at the beginning of the string going all the way to the end. Since you have a positive lookbehind (INSERT INTO), the match starts at text which is not at the beginning. Likewise, the lookahead at the end means there is no match at the end either.

split works as expected because it doesn't require the match to start at the beginning.

于 2012-04-28T19:47:07.580 回答