OR em 'expr match'

6

Estou confuso sobre por que isso não corresponde:

expr match Unauthenticated123 '^(Unauthenticated|Authenticated).*'

gera 0.

    
por stracktracer 14.12.2015 / 14:54

3 respostas

5

Seu comando deve ser:

expr match Unauthenticated123 'Unauthenticated\|Authenticated'

Se você quiser o número de caracteres correspondentes.

Para que a parte da string (Unauthenticated) retorne use:

expr match Unauthenticated123 '\(Unauthenticated\|Authenticated\)'

De info coreutils 'expr invocation' :

'STRING : REGEX'
     Perform pattern matching.  The arguments are converted to strings
     and the second is considered to be a (basic, a la GNU 'grep')
     regular expression, with a '^' implicitly prepended.  The first
     argument is then matched against this regular expression.

     If the match succeeds and REGEX uses '\(' and '\)', the ':'
     expression returns the part of STRING that matched the
     subexpression; otherwise, it returns the number of characters
     matched.

     If the match fails, the ':' operator returns the null string if
     '\(' and '\)' are used in REGEX, otherwise 0.

     Only the first '\( ... \)' pair is relevant to the return value;
     additional pairs are meaningful only for grouping the regular
     expression operators.

     In the regular expression, '\+', '\?', and '\|' are operators
     which respectively match one or more, zero or one, or separate
     alternatives.  SunOS and other 'expr''s treat these as regular
     characters.  (POSIX allows either behavior.)  *Note Regular
     Expression Library: (regex)Top, for details of regular expression
     syntax.  Some examples are in *note Examples of expr::.
    
por 14.12.2015 / 15:04
5

Observe que match e \| são extensões GNU (e o comportamento de : (o equivalente a match padrão) quando o padrão começa com ^ varia com as implementações). Normalmente, você faria:

expr " $string" : " Authenticated" '|' " $string" : " Unauthenticated"

O espaço principal é evitar problemas com valores de $string que iniciam com - ou são expr operadores, mas isso significa que ele adiciona um ao número de caracteres que estão sendo correspondidos.

Com o% GNUexpr, você escreveria:

expr + "$string" : 'Authenticated\|Unauthenticated'

O + força $string a ser considerado uma string, mesmo que seja um operador expr . expr expressões regulares são expressões regulares básicas que não possuem um operador de alternância (e onde | não é especial). A implementação GNU tem como \| como extensão.

Se tudo o que você quer é verificar se $string começa com Authenticated ou Unauthenticated , é melhor usar:

case $string in
  (Authenticated* | Unauthenticated*) do-something
esac
    
por 14.12.2015 / 15:49
2

$ expr match "Unauthenticated123" '^\(Unauthenticated\|Authenticated\).*' você tem que escapar com \ o parêntese e o tubo.

    
por 14.12.2015 / 15:06