4

Why does the following regular expression print valid, when the name is hdpworker01?

name=hdpworker01
[[ $name =~ worker[[:digit:]] ]] && echo valid

What I try to do is print valid only if the name matches worker[0-999].

Example expected results:

  • For name=worker01: valid
  • For name=hdpworker01: no output
8

A regular expression is not anchored to the start or end of a string by default. This is different from e.g. filename globbing patterns. This means that the expression may match anywhere in the given string.

To have your expression anchored to the start of the string, use

^worker[[:digit:]]

To additionally anchor it to the end of the string and to allow for one to three digits, use

^worker[[:digit:]]{1,3}$

If you want to match worker10 but not worker01 or worker003 (no zero-filled numbers), use

^worker([0-9]|[1-9][0-9]{1,2})$
1

Anchor the regex on both sides.

^worker[[:digit:]]$
1

why the following regular expression print valid , while name is hdpworker01

Why? Because the regex is not anchored, i.e. it does not define the start (or end) of the string that is supposed to be matched. The regex worker will match if any part of the string being matched is worker. It will match hdpworkeranything as well as worker as many other variations. To match an string that start with worker make the regex contain a ^, like:

^worker

If you want to match (up to) 3 digits after the word worker, you may use:

^worker[0-9]{0,3}$

However, it will be wise to capture the number with parenthesis and place the regex inside a variable (using a variable is the present best practice):

re='^worker([0-9]{0,3})$'

The $ means that the string should end at that point.
The match will become:

[[ $str =~ $re ]] && n=$((10#${BASH_REMATCH[1]}+0)) || n=-1

what I try to do is to print valid only if name is worker[0-999]

And that will allow to check the number n range:

(( 0 <= n && n <= 999 )) && echo "valid with n=$n"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.