Regular Expression in Bash (grouping)

225 views Asked by At

So here is what I have:

regex="^([A-Z]{2,8}-[0-9]{1,4}[[:space:]])+[[:alnum:]]+$"
message="TEST-121 Testing" 
echo $message | grep -qE "$regex"

This works. However, I need something like below:

message="TEST-132 Testing is going on". 

My current regex, return 1 and this should return 0. And the below one as well:

message+"TEST-111 TEST-132 Stack overflow rocks "

The above regex only suffices one word after the first string, so need help in updating [[:alnum:]] to something which can parse more words and not just one.

Thanks in advance.

2

There are 2 answers

0
nu11p01n73R On

Add a [:space:] to the last character class as

$ regex="^([A-Z]{2,8}-[0-9]{1,4}[[:space:]])+[[:alnum:][:space:]]+$"

$ message="TEST-132 Testing is going on" 
$ echo $message | grep -E "$regex"
TEST-132 Testing is going on

$ message="TEST-111 TEST-132 Stack overflow rocks "   
$ echo $message | grep -E "$regex"
TEST-111 TEST-132 Stack overflow rocks
0
anubhava On

This regex should wwork for all the input strings:

regex='^[A-Z]{2,8}-[0-9]{1,4}([[:blank:]]+[^[:blank:]]*)+$'

Example:

echo "TEST-111 TEST-132 Stack overflow rocks " | 
    grep -oE '^[A-Z]{2,8}-[0-9]{1,4}([[:blank:]]+[^[:blank:]]*)+$'
TEST-111 TEST-132 Stack overflow rocks