regex - Perl 正则表达式匹配字符串不以某物结尾

请问哪个正则表达式能正确匹配?

我想识别不以特定文本 (_array) 结尾的字符串。我试过使用负前瞻,但我无法让它工作。 (请注意,显而易见的答案是执行相反的操作 (m{_array$}),但我不想这样做是有原因的)。

 use strict;
 use warnings;
 while(<DATA>) {
    #
    ## If the string does not end with '_array' print No, otherwise print Yes
    m{(?!_array)$} ? print "No  = " : print "Yes = ";
    print;
 }
 __DATA__
 chris
 hello_world_array
 another_example_array
 not_this_one
 hello_world

我想要的输出应该是:

 No  = chris
 Yes = hello_world_array
 Yes = another_example_array
 No  = not_this_one
 No  = hello_world

最佳答案

你需要在背后消极看待。即,您想搜索不在 _array 之前的字符串结尾。

请注意,您需要先chomp 该行,因为$ 将匹配尾随换行符前后。

条件运算符旨在返回一个 - 它不是if 语句的简写。

use strict;
use warnings;

while (<DATA>) {
  chomp;
  # If the string does not end with '_array' print No, otherwise print Yes
  print /(?<!_array)$/ ? "No  = $_\n" : "Yes = $_\n";
}

__DATA__
chris
hello_world_array
another_example_array
not_this_one
hello_world

输出

No  = chris
Yes = hello_world_array
Yes = another_example_array
No  = not_this_one
No  = hello_world

https://stackoverflow.com/questions/14234932/

相关文章:

regex - 如何在 Perl 中的正则表达式匹配后打印行?

c# - 添加 const 关键字会中断 Path.Combine 调用

exception - gwt、rpc 服务、StatusCodeException 和无可用日志

php - Magento:通过事件以编程方式更新购物车

ruby-on-rails - 即使表中有用户名,也没有用户名字段

visual-c++ - 当类向导被破坏时,将计时器 (WM_TIMER) 处理程序添加到 Visu

jsf - 如何通过 primefaces 中的 beans 在 selectOneRadio/se

r - 使用 theme_wsj {ggthemes} 时如何使 xlab 和 ylab 可见?

r - 生成给定百分位数的分布

r - 如何按位置排除向量中的多个元素?