有没有一种简单的方法可以匹配每行超过1次指定字符串的出现?

DBM*_*s99 1 regex perl

我一直在尝试做以下事情:

 if (m/(foobar)\{2,}?/ig)
Run Code Online (Sandbox Code Playgroud)

处理文件并仅对那些存在超过2个'foobar'的行进行操作.不工作 - 我怀疑它可能需要"反向引用"技术,但如果有人能用简单的匹配技术做到这一点,我会感到惊喜

set*_*eth 7

您不能使用{}量词,因为这仅用于重复.(例如"foobar foobar foobar").如果你的字符串有"fooobar更多foobar",它将无法匹配.最简单,最清晰的方法是将匹配推送到这样的数组中:

 my @matches = $str =~ /(foobar)/ig;
Run Code Online (Sandbox Code Playgroud)

然后@matches将举行所有比赛.

if (@matches >=2) {
   # work in special sauce
}
Run Code Online (Sandbox Code Playgroud)


小智 7

这很简单:

if ( $str =~ /foobar.*foobar/ ) {
Run Code Online (Sandbox Code Playgroud)

当然 - 你的foobar可能有点复杂,所以让我们使用反向引用:

if ( $str =~ /(foobar).*\1/ ) {
Run Code Online (Sandbox Code Playgroud)

如果你想让它匹配,如果这是5次排队怎么办?简单:

if ( $str =~ /(foobar)(.*\1){4}/ ) {
Run Code Online (Sandbox Code Playgroud)

或更好:

if ( $str =~ /(foobar)(?:.*\1){4}/ ) {
Run Code Online (Sandbox Code Playgroud)

有关?:和其他此类魔法琴弦的详细信息,您可以使用perldoc perlre.