Reputation: 3151
In the below code, either T1 should be set or T2 must follow the regex, else print "error", but it doesn't work.
And is there an better way to check if T2 has pattern <a string with underscore >:<space separated strings>;
please note the colon and semicolon.
#!/bin/bash
T1="TEST"
T2="TST_1:one two three;"
if [[ -z ${T1} && ! ${T2} =~ .*":".*";" ]]; then
echo "error"
exit 1
fi
Upvotes: 1
Views: 118
Reputation: 483
Here's what worked for me:
re="^.+_.+:.+( .+)+;$"
if [[ -z "$T1" && ! $T2 =~ $re ]]; then
echo "Error"
exit 1
fi
For that regex, the caret ("^") means the start of the line. Then there's ".+" which is any character (the period) 1 or more times (the plus). Then there's an underscore and another group of 1 or more characters followed by the colon. After that, you have a group of 1 or more characters followed by at least one set of a space and some characters. Then the semicolon and a dollar sign meaning that has to be the end of the line.
With your sample, it breaks down as follows:
^.+ - "TST" at the beginning of the line
_ - the underscore
.+ - "1"
: - the colon
.+ - "one"
( .+)+ - inside the parentheses, there's a space and a .+
meaning one or more characters. So that's " two".
But the plus after the right parenthesis means one
or more of that group so it also applies to " three"
as well as any other groups of letters that might
follow, separated by spaces.
;$ - the trailing semicolon, at the very end of the line.
This will allow for any set of characters at the start (as long as there's an underscore), the colon, and any number of groups of characters separated by a space. And the trailing semicolon, of course.
btw, if you want to limit things to letters, numbers, and an underscore (so that "t#t_1:..." would fail), switch the periods for "\w" which is shorthand for [a-zA-Z0-9_].
If you want to fool around with regular expressions, a debugger like https://www.debuggex.com/?flavor=pcre can be useful.
Hope this helps!
Upvotes: 0
Reputation: 784938
You can use this regex:
re='^[^:_]+_[^:_]:[^[:blank:];]+([[:blank:]]+[^[:blank:];]+)+;$'
T1="TEST"
T2="TST_1:one two three;"
if [[ -z "$T1" && ! $T2 =~ $re ]]; then
echo "error"
exit 1
fi
Upvotes: 1