4

cygwinでは、これは一致を返しません:

$ echo "aaab" | grep '^[ab]+$'

しかし、これは一致を返します:

$ echo "aaab" | grep '^[ab][ab]*$'
aaab

2つの表現は同一ではありませんか?文字クラスを2回入力せずに「文字クラスの1つ以上の文字」を表現する方法はありますか(秒の例のように)?

このリンクによると、2つの式は同じである必要がありますが、Regular-Expressions.infoはcygwinのbashをカバーしていない可能性があります。

4

3 に答える 3

7

grepマッチングには複数の「モード」があり、デフォルトでは基本セットのみを使用します。これは、エスケープされない限り、いくつかのメタ文字を認識しません。+grepを拡張モードまたはperlモードにして、評価させることができます。

差出人man grep

Matcher Selection
  -E, --extended-regexp
     Interpret PATTERN as an extended regular expression (ERE, see below).  (-E is specified by POSIX.)

  -P, --perl-regexp
     Interpret PATTERN as a Perl regular expression.  This is highly experimental and grep -P may warn of unimplemented features.


Basic vs Extended Regular Expressions
  In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).

  Traditional egrep did not support the { meta-character, and some egrep implementations support \{ instead, so portable scripts should avoid { in grep -E patterns and should use [{] to match a literal {.

  GNU  grep -E attempts to support traditional usage by assuming that { is not special if it would be the start of an invalid interval specification.  For example, the command grep -E '{1' searches for the two-character string {1 instead of reporting a syntax
       error in the regular expression.  POSIX.2 allows this behavior as an extension, but portable scripts should avoid it.

egrepまたは、の代わりにを使用することもできますgrep -E

于 2011-04-13T14:22:53.433 に答える
6

?基本的な正規表現では+、メタ文字、、、、、、およびは特別な意味を 失い ます。代わりに、バックスラッシュバージョン\?、、、、、、 およびを使用してください。{|()\+\{\|\(\)

したがって、バックスラッシュバージョンを使用します。

$ echo aaab | grep '^[ab]\+$'
aaab

または、拡張構文をアクティブにします。

$ echo aaab | egrep '^[ab]+$'
aaab
于 2011-04-13T14:22:46.963 に答える
2

バックスラッシュによるマスキング、または拡張grepとしてのegrep、エイリアスgrep -e

echo "aaab" | egrep '^[ab]+$'

aaab

echo "aaab" | grep '^[ab]\+$'

aaab

于 2011-04-13T14:23:51.310 に答える