Sheraff Sheraff - 1 year ago 131
Bash Question

Bash regex match with word boundary

I would like to match the following expression in bash:


Really all I want to know is whether one of the words of the string tested is one of the words described in this regex (
, ...). And there seems to be an issue with the word boundaries.

The test I use is
[[ $name =~ $re ]] && echo "yes"
is any string and
is my regex expression.

What am I missing?

Answer Source

\b is a PCRE extension; it isn't available in ERE(Extended Regular Expressions), which the =~ operator in bash's [[ ]] syntax uses.

However, that extension doesn't actually have very much expressive power -- you can write any PCRE that uses it as an equivalent ERE. Better, though, is to step back and question the underlying assumptions: When you say "word boundary", what do you really mean? If all you care about is that if this starts and ends either with whitespace or the beginning or end of the string, then you don't need the \b operator at all:


Note that I took out the initial ^.* and ending .*$, since those constructs are self-negating when doing an otherwise-unanchored match; the .* makes the ^ that immediately precedes it meaningless, and likewise the .* just before the final $.

Now, if you want an exact equivalent to \b when placed immediately before a word character at the beginning of a sequence, then we get something more like:


...and, likewise, when immediately after a word character at the end of a sequence:


Both of these are somewhat degenerate cases -- there are other situations where emulating the behavior of \b in ERE can be more complicated -- but they're the only situations your question appears to present.

Note that some implementations of \b would have better support for non-ASCII charactersets, and thus be better described with [^[:alnum:]_] rather than [^a-zA-Z0-9_], but it's not well-defined here which implementation you're coming from or comparing against.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download