0

捕捉模式的正则表达式是什么,如果它后面跟着一些东西?否则,捕获模式的第一次出现。

例子

  • 在以下位置找到“FL”:CA 和 FL(较小)州位于沿海地区。
  • 在以下位置找到“CA”:CA 和 FL 州位于沿海地区。

编辑例如:

  • 查找 FL 后跟 '(smaller)'
  • 查找 CA,因为 FL 后面没有 '(smaller)'
4

1 回答 1

1

这对我来说并不完全清楚,但这里有一个尝试,有perl味道:

内容script.pl

use warnings;
use strict;

while ( <DATA> ) { 
    chomp;
    if ( m/
            (?(?=.*\(smaller\))                 # Positive look-ahead conditional expression.
                \b([[:upper:]]+)\s+\(smaller\)  # If succeed, match previous word only in uppercase.
                    |                           # Or
                \b([[:upper:]]+)\b)             # If failed, match first word in uppercase found.
        /x ) {    
        printf qq[%s -> %s\n], $_, $1 || $2;    # $1 has first conditional, $2 the second one.
    }   
}

__DATA__
The states of CA and FL (smaller) are along coasts.
The states of CA and FL are along coasts.

像这样运行它:

perl script.pl

具有以下输出:

The states of CA and FL (smaller) are along coasts. -> FL
The states of CA and FL are along coasts. -> CA

用单线更新(输出相同):

perl -lne '
    printf qq[%s -> %s\n], $_, $1 || $2 
        if m/(?(?=.*\(smaller\))\b([[:upper:]]+)\s+\(smaller\)|\b([[:upper:]]+)\b)/
' infile
于 2012-04-26T14:35:46.390 回答