0

何かが続く場合、パターンをキャッチする正規表現は何ですか? それ以外の場合は、パターンの最初の出現をキャッチします。

  • 'FL' の検索: CA と FL (より小さい) の州は海岸沿いにあります。
  • 「CA」の検索: CA と FL の州は海岸沿いにあります。

たとえば、次のように編集します。

  • FL の後に '(smaller)' が続くものを検索します
  • FL の後に '(smaller)' がないため、CA を検索します。
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 に答える