如何匹配与 Perl 中特定模式不匹配的字符串? [英] How can I match strings that don't match a particular pattern in Perl?

查看:64
本文介绍了如何匹配与 Perl 中特定模式不匹配的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用正则表达式很容易匹配除给定字符之外的任何内容.

I know that it is easy to match anything except a given character using a regular expression.

$text = "ab ac ad";
$text =~ s/[^c]*//g; # Match anything, except c.

$text is now "c".

我不知道如何排除"字符串而不是字符.我将如何匹配任何东西,除了‘ac’"?尝试了 [^(ac)] 和 [^"ac"] 没有成功.

I don't know how to "except" strings instead of characters. How would I "match anything, except 'ac'" ? Tried [^(ac)] and [^"ac"] without success.

有可能吗?

推荐答案

以下解决了 Bart K. 评论中描述的第二种意义上的问题:

The following solves the question as understood in the second sense described in Bart K. comment:

>> $text='ab ac ad';
>> $text =~ s/(ac)|./\1/g;
>> print $text;
ac

另外,'abacadac' -> 'acac'

不过应该​​注意的是,在大多数实际应用中,否定前瞻被证明比这种方法更有用.

It should be noted though that in most practical applications negative lookaheads prove to be more useful than this approach.

这篇关于如何匹配与 Perl 中特定模式不匹配的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆