Reputation: 289
How to verify if the string also starts and ends with one or more space(s) ?
if [[ $username =~ [^0-9A-Za-z]+ ]]
(basically input should be alphanumeric, no spaces anywhere, even in the beginning or in the end, and no commas, underscores, hiphens etc)
The above regex unfortunately does NOT match leading & trailing spaces, but it matches spaces in between ?
Without awk, sed, is there any way I can fix the above regex to match leading & trailing spaces also ?
Thanks in advance
Upvotes: 4
Views: 4572
Reputation: 289
Thanks @Glenn if [[ $username =~ [^0-9A-Za-z]+ ]]
This was my original regex, and I want the user to only enter alphanumerics (all others should not be accepted including spaces, underscores etc). I am using a read inside an infinite while loop and terminating only on valid input.
The regex matches all non alphanumerics and even strings with space in between as expected but it was not matching entries with leading and trailing spaces (I thought so).
Then I have realized that its not the regex but the "read" command which was automatically trimming the leading and trailing spaces, so by the time it comes to regex, variable itself was trimmed.
"The trick around this, is to redefine your IFS (Internal Field Separator) variable. By default, IFS is set to the space, tab and newline characters to delimit words for the read command." got this from this blog
http://fahdshariff.blogspot.in/2008/06/read-file-without-trimming-leading.html, and I have fixed my script accordingly.
Thanks for following up and explaining the details !!
Upvotes: 0
Reputation: 246877
Bash regexes can be tricky with quoting: regex metachars must NOT be quoted, but, since whitespace is significant in the shell, spaces must be quoted. This regex matching a string beginning and ending with a space:
[[ $s =~ ^" ".*" "$ ]] && echo y
To test if a string contains a space, do one of:
[[ $s =~ [[:space:]] ]] && echo y
[[ $s == *" "* ]] && echo y
Upvotes: 5
Reputation: 798754
(basically input should be alphanumeric, no spaces anywhere, even in the beginning or in the end, and no commas, underscores, hiphens etc)
Uh, unless I'm missing something...
if ! [[ $username =~ ^[0-9a-zA-Z]+$ ]]
Upvotes: 1