我有一个正则表达式
(\\w+[ ]*|-\\w+[ ]*)(!=|<=|>=|=|<|>| not in | in | not like | like )(.*)
这有3个部分以逗号分隔。
当我尝试将其与
之类的东西相匹配时product(getProduct_abc) in (Xyz)
它与正则表达式不匹配。
但是当我尝试匹配时
100=product(getProduct_abc) in (Xyz)
它与完美匹配。
正则表达式有什么问题?
答案 0 :(得分:0)
本身没有任何错误,正则表达式。它只是与指定的字符串不匹配。
你需要找到一个关于正则表达式的好参考并学习基础知识。一个是http://www.regular-expressions.info/。对于初学者来说,这可能是也可能不是一个很好的参考。 (我正在使用他的RegexBuddy工具来测试你的正则表达式。)
以下是表达式的粗略细分:
字符串'product(getProduct_abc)in(Xyz)'无法匹配,因为在'in
'运算符之前,不仅仅是“word”字符。括号不被视为“单词”字符,因此导致匹配失败。
第二个字符串('100 = product(getProduct_abc)in(Xyz)')匹配,因为它使用equals('=')作为第二个捕获组的匹配运算符,'100'是所有的字符串“单词“字符,'='后的所有内容与”任意字符“部分匹配,因此匹配成功。请注意,根据字符串结尾的处理方式,如果字符串位于字符串的最后,某些语言甚至可能与该字符串不匹配。
如果第一个字符串假定匹配,那么您需要与业务用户核实。也许他们也是正则表达式的初学者,并给了你一个不起作用。 ; - )
答案 1 :(得分:0)
这就是我所看到的:
'100=product(getProduct_abc) in (Xyz)'
Group1 match = '100'
Group2 match = '='
Group3 match = 'product(getProduct_abc) in (Xyz)'
'product(getProduct_abc) in (Xyz)'
^
Fails here on Group1 match because parenthesis are not included in this group
您可以通过强制字符串中最后一次出现1,2,3组匹配来解决问题 修复/重写等价的Group1匹配并分离组,可以重新组合它们以强制进行最后一次匹配。
rxP1 = '(?:-?[\w()]+\ *)';
rxP2 = '(?:!=|<=|>=|=|<|>| not in | in | not like | like )';
rxP3 = '(?:.*?)';
rxAll = /(?:$rxP1$rxP2$rxP3)*($rxP1)($rxP2)($rxP3)$/;
Perl:
use strict;
use warnings;
my @samples = (
'product(getProduct_abc) in (Xyz1)',
'100=product(getProduct_abc) in (Xyz2)',
'100 like = != not like >product(getProduct_abc) in (Xyz3)',
);
my $rxP1 = '(?:-?[\w()]+\ *)';
my $rxP2 = '(?:!=|<=|>=|=|<|>| not in | in | not like | like )';
my $rxP3 = '(?:.*?)';
for (@samples)
{
if ( /(?:$rxP1$rxP2$rxP3)*($rxP1)($rxP2)($rxP3)$/ ) {
print "\n1 = '$1'\n";
print "2 = '$2'\n";
print "3 = '$3'\n";
}
}
输出:
1 = 'product(getProduct_abc)'
2 = ' in '
3 = '(Xyz1)'
1 = 'product(getProduct_abc)'
2 = ' in '
3 = '(Xyz2)'
1 = 'product(getProduct_abc)'
2 = ' in '
3 = '(Xyz3)'