perl 正则表达式,它将标识包含|但仅当其不在文本中的“任何其它地方”内时

nhaq1z21  于 2023-01-13  发布在  Perl
关注(0)|答案(1)|浏览(103)

我正在尝试设计一个Perl正则表达式作为if条件来标识|但如果|包含在带引号的字符串中的任何位置,如'It went〉|碰撞|当它掉在地板上
输入示例如下
这应匹配:

action 71|55|279|286|155|57|343

这不应匹配:

action mud_destroyset($me,$arg,$arg1,$arg2,'gun','2','There is an almighty >| CRASH |< . When the smoke clears, both door and sphere are gone...','You hear the >| CRASH |< of a cannon going off in the distance.','',0,$cid,$oc) ;

我试过如下的negative lookbehind regex,广泛地摆弄,失败了。我甚至问了ChatGPT,它也失败了。
这些没有工作(第一个是ChatGPT解决方案,第二个是我的尝试):

^(?:(?!'\|).)*\|
(?<!').+\|.+

https://regex101.com/r/1o0SOM/1
https://regex101.com/r/z5Xz83/1
感谢帮助!

pu82cl6c

pu82cl6c1#

一种方法是非破坏性地删除单引号中的任何内容(包括引号),然后查找管道:

index($txt =~ s/'[^']*'//gr, "|") != -1

运行示例:

use strict;
use warnings;

my @texts = ("action 71|55|279|286|155|57|343",
             "action 'There is this >| CRASH |< .'");

for my $txt (@texts) {
    print index($txt =~ s/'[^']*'//gr, "|") != -1 ? "yes\n" : "no\n";
}

它给出了

yes
no
  • ':文字单引号
  • [^']*:除单引号外的任何内容,尽可能多次重复
  • ':还是一个单引号
  • “g”标志:全局替换
  • “r”标志:非破坏性,即返回新字符串

index函数查找子字符串(“|“),如果在搜索的字符串中找不到它,则返回-1。

相关问题