[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Word boundary anchors \< and \> not parsed correctly on the right si
Re: Word boundary anchors \< and \> not parsed correctly on the right side of =~
Tue, 10 Jul 2018 10:37:42 -0400
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, address@hidden wrote:
> Bash Version: 4.4
> Patch Level: 19
> Release Status: release
> 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
> as â€˜==â€™ and â€˜!=â€™. When it is used, the string to the right of the
> 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:
> [[ '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.
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU address@hidden http://tiswww.cwru.edu/~chet/
Re: Word boundary anchors \< and \> not parsed correctly on the right side of =~,
Chet Ramey <=