【问题标题】:Is there a way to do a negative match on a string using a positive match regex operator?有没有办法使用正匹配正则表达式运算符对字符串进行负匹配?
【发布时间】:2012-10-15 18:42:02
【问题描述】:

具体来说,有没有办法实现相当于

my $string = 'this is some example text';
my $match = qr/foobar/;
print 'success' if $string !~ $match;

仅使用 =~,不使用否定运算符?

具体来说,我需要确保字符串与 supplied 值不匹配,并且测试函数采用正则表达式对象,并将它们积极应用于该值。 该值根本不能出现在搜索的字符串中,这使前瞻和后瞻断言变得复杂。

以下内容可能是一个很好的测试:

my $string = 'this is some example text';
my $match =~ qr/foobar/;
# $negated_match contains $match, or some transformed variation of it
my $negated_match = qr/$YOUR_REGEX_HERE/; 
die 'failure' if $string =~ $match;
print 'success' if $string =~ $negated_match;

我怀疑有一种方法可以通过环视断言来做到这一点,但还没有弄明白。 perl 特定的答案是可以接受的。

【问题讨论】:

  • 我不太确定我明白你的问题。听起来你可以使用print 'success' unless $string =~ $match 吗?换句话说,只是颠倒逻辑。我认为你最好尝试展示你正在尝试做的事情。
  • @TLP,据我了解,他将$match 传递到一些执行print 'success' if $string =~ $match 的代码中。他想将if 更改为unless,但他无法控制那部分代码(可能在模块中),只能控制$match 的内容。
  • 问题是我有一个接受正则表达式对象,然后将它们与字符串。能够在不更改系统的情况下提供负面测试用例很有用。

标签: regex perl regex-negation regex-lookarounds


【解决方案1】:
my $string = 'this is some example text';
my $match = qr/^(?!.*foobar)/s;
print 'success' if $string =~ $match;

【讨论】:

  • /s 可以使用(?s:...) 移动到模式中
  • 天啊!这很简单,我真的应该想出它。
猜你喜欢
  • 2015-07-31
  • 1970-01-01
  • 2012-06-05
  • 2013-12-25
  • 1970-01-01
相关资源
最近更新 更多