1

I cant really explain but check out the following:

name=$1
pat="\b[0-9a-zA-Z_]+\b"

if [[ $name =~ $pat ]]; then
  echo "$name is ok as user name"
else
  echo "$name is not ok as user name"
  exit 1
fi

Test run:

./script test_user+
test_user+ is ok as user name

The username with a + sign should not match that regexp.

Istvan
  • 7,500
  • 9
  • 59
  • 109

3 Answers3

5

First of all:

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

(From Bash regex match with word boundary)

Second, you don't want word boundaries (\b) if you wish to force the entire string to match. You want to match the start (^) and end ($):

pat="^[0-9a-zA-Z_]+\$"
Community
  • 1
  • 1
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
0

if you dont want word bondry (guessed as you are trying username match) please use

^[0-9a-zA-Z_]+$
Suneer
  • 106
  • 1
  • 5
0

Contrary to the OP's experience and other answer it seems \b is supported on Ubuntu 14.04, bash 4.3.11 as word boundary. Here is a sample:

re='\bb[0-9]+\b'

[[ 'b123' =~ $re ]] && echo "matched" || echo "nope"
matched

[[ 'b123_' =~ $re ]] && echo "matched" || echo "nope"
nope

Even \< and \> also work fine as word boundaries:

re='\<b[0-9]+\>'

[[ 'b123' =~ $re ]] && echo "matched" || echo "nope"
matched

[[ 'b123_' =~ $re ]] && echo "matched" || echo "nope"
nope

However support of \b is specific to certain OS only. e.g. on OSX following works as word boundary:

[[ 'b123' =~ [[:\<:]]b[0-9]+[[:\>:]] ]] && echo "matched" || echo "nope"
matched

[[ 'b123_' =~ [[:\<:]]b[0-9]+[[:\>:]] ]] && echo "matched" || echo "nope"
nope
anubhava
  • 761,203
  • 64
  • 569
  • 643