bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Word boundary anchors \< and \> not parsed correctly on the right si


From: Chet Ramey
Subject: Re: Word boundary anchors \< and \> not parsed correctly on the right side of =~
Date: Tue, 10 Jul 2018 10:37:42 -0400
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.0) Gecko/20100101 Thunderbird/52.9.0

On 7/9/18 9:46 PM, marcelpaulo@gmail.com wrote:

> Bash Version: 4.4
> Patch Level: 19
> Release Status: release
> 
> Description:
> Word boundary anchors \< and \> are not parsed correctly on the right side of 
> a =~ regex match expression. 

Bash assumes Posix regular expressions (EREs), and those don't have any
kind of boundary anchors.

> This evaluates as false:
> 
>     [[ 'foo bar' =~ \<foo\> ]]

As it should; in a Posix RE, you're matching a literal <foo>.

> From the bash reference manual:
> 
>     An additional binary operator, ‘=~’, is available, with the same 
> precedence
>     as ‘==’ and ‘!=’. When it is used, the string to the right of the 
> operator
>     is consid- ered an extended regular expression and matched accordingly (as
>     in regex 3)).

A Posix extended regular expression.

> 
> Reading regex(3), I presumed the regexes would be parsed as C strings, so the
> backslashes would need to be escaped:
> 
>     [[ 'foo bar' =~ \\<foo\\> ]]
> 
> but this results in:
> 
>     bash: syntax error in conditional expression: unexpected token `<'
>     bash: syntax error near `\\<f'

The `<' is not a character that's special to Posix EREs, so it retains its
usual meaning as an operator and needs to be quoted.

>     
> If the regex is stored in a variable, the expression evaluates as true:
> 
>     re='\<foo\>'
>     [[ 'foo bar' =~ $re ]]

Yes, this is the usual idiom to pass special characters that may include
quotes or operators to the regular expression engine.

Bash supports the notion that you can quote characters that are special to
EREs to match them literally. To do this, it has to know which characters
are special to EREs, and it uses POSIX to determine those characters. A
system can add extensions to the standard POSIX interface, but bash can't
assume the presence of any such extension.

> 
> Treating the regex as C strings works for the \b anchor, so that this 
> evaluates as true:

Because `b' is not an operator and doesn't need to be escaped.

Chet

-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]