2011-04-13 1 views
3

,이 일치 반환하지 않습니다정규 표현식의 일부로 문자 클래스와 함께 더하기 기호를 어떻게 사용합니까? Cygwin에서의

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

을하지만이 일치 반환 않습니다

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

이 동일한 두 개의 표현되지 않습니다? 문자 클래스를 두 번 입력하지 않고 "문자 클래스의 하나 이상의 문자"를 표현할 수있는 방법이 있습니까?

this link에 따르면 두 표현식은 동일해야하지만 Regular-Expressions.info는 cygwin에서 bash를 포함하지 않을 수 있습니다. 기본 정규 표현식에서

답변

6

grep이 일치하는 다수의 "모드"가, 기본적으로 단지 기본 세트를 사용하는 탈출하지 않는 한 많은 수의 메타 문자를 인식하지 못합니다. 확장 또는 펄 모드에 grep을 넣어서 +을 평가할 수 있습니다. 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 사용할 수 있습니다.

6

는 메타 문자는 ?+{|, () 은 특별한 의미를 잃게; 대신 백 슬래시 버전 \?, \+, \{, \|, \(\)을 사용하십시오.

는 그래서 백 슬래쉬 버전 사용

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

또는 확장 구문을 활성화 :

$ echo aaab | egrep '^[ab]+$' 
aaab 
2
백 슬래시

마스킹을, 또는 확장 그렙, 별명 grep -e로 egrep을 :

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

AAAB

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

AAAB

+2

당신이'의미 그렙 -E' –

관련 문제