[英]perl regex: negative lookahead between two characters
您如何在正则表达式中的两个字符之间包含模式?
假设我想打印以下文本中的所有内容,除了" "
之间的单词
This is an "example".
This "is" "an" example.
"This" is an example.
到目前为止,这是我尝试过的方法,但是我认为我缺少了一些东西:
m/(?!"(.*)").*/g
$s = 'This "is" "an" example';
@words = ($s =~ /"([^"]*)"/g);
@words
包含" "
之间的所有单词
您可以使用s///
删除双引号之间的那些子字符串。
这是一个测试程序:
#!/usr/bin/perl
use strict;
use warnings;
use feature qw(switch say);
use Data::Dumper;
while (<DATA>) {
chomp;
s/"[^"]*"//g;
print "$_\n";
}
__DATA__
This is an "example".
This "is" "an" example.
"This" is an example.
结果:
$ perl t.pl
This is an .
This example.
is an example.
类似于重新评估的解决方案:
@words_in_quotes = ($s =~ /"(.*?)"/g)
无需后置断言。
这几乎是XY Problem
的定义
断言是正则表达式的一种高级功能,对于您必须解决的大多数问题,断言都是很有可能不需要的。
相反,我将重点放在基础知识上,可能从贪婪和非贪婪匹配开始。
@quoted_words = ($s =~ /"(.*?)"/g);
任何时候,您都可以使用量词*
或+
,它会尝试尽可能多地匹配,然后回溯。 通过减少应匹配的字符类型并添加边界条件,或通过添加问号将匹配更改为非贪婪,可以限制此限制。 *?
或+?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.