
( _my_command_c_option ! ~ “^user” ) { error+=”The user name must start with user”
} else {
note+=”The user name chosen was “ + ${_my_command_c_option}
}
Note the use of the “!” operator in the test: this reverses the comparison, so an error is given if the value in _my_command_c_option does not match the regular expression. The example is presented this way since you may not want to always print the note - the else and the note can be skipped.
The test above compares the value in _my_command_c_option against “^user”. This expression is anchored to the start of what we are comparing against, so matches must start with “user”. It is important to understand that anything can be after the “user”. Unlike some other regular expressions, such as shell regular expressions, extended regular expressions do not require a wildcard operator after the “user” to get a match.
( _my_command_c_option ! ~ “^[[:alpha:]][[:digit:]]*” ) {
error+=”The user name must start with letter followed by only digits” } else {
note+=”The user name chosen was “ + ${_my_command_c_option}
}
In the above example you might think that the regular expression matches something that starts with a letter followed by one or more numbers. It doesn’t actually mean that. It really matches something that starts with a letter followed by zero or more numbers. The above regular expression would match just a single letter.
If you want to only allow user names in the form of a single letter (upper or lower case) followed by exactly six numbers, you would be
^[[:alpha:]][[:digit:]][[:digit:]][[:digit:]][[:digit:]][[:digit:]][[:digit:]]$
The expression is anchored at the start and the end, so we know what we will be matching against will match exactly or not at all. There are no wildcards or other constructs that can cause problems for us. The above regular expression will only match something that starts with a single letter followed exactly six digits.
If your requirements aren’t that strict, you can use a slightly different expression:
"^[[:alpha:]][[:digit:]]+[[:digit:]]$"
This matches a user name starting with a letter, followed by one or more numbers, and ending with a number. This will match the following: “u12”, “u123”, and “u1234”. The only requirements for a match are that the user name starts with a letter and contains at least two digits69 after it (with nothing else after that.)
69The regular expression “[[:digit:]]+[[:digit:]]” requires that there be at least a starting and ending number there can be 0 or more numbers in between.
145