简体   繁体   中英

shell script odd regex

i have some regex that is behaving oddly in my shell script i have variables, and i have tried every what way to get them to behave, and they dont seem to do any regex, and i know my regex quite well thanks to regex101 , here is what a sample looks like

fname="direcheck"
FIND="*"
if [[ $fname =~ $FIND ]]; then
echo "no quotes"
fi

if [[ "$fname" =~ "$FIND" ]]; then
echo "with quotes"
fi

right now it will display nothing if i change find to

FIND="[9]*"

then it prints no quotes if i say

FIND="[a-z]*"

then it prints no quotes

if i say

FIND="dircheck"

then nothing prints

if i say

FIND="*ck"

then nothing prints

I don't get how this regex is working

how do i use these variables, and what is the proper syntax ?

  • * and *ck are invalid regular expressions. It would work (with no quotes) if you were comparing with == , not =~ . If you want to use the same functionality that you get in == for them, the equivalent regexps are .* and .*ck .

  • [9]* is any number (including zero) of characters that are 9 . There is zero characters 9 in your direcheck , so it matches. (Edited from brainfart, thanks chepner)

  • dircheck is not found in direcheck , so not printing anything is hardly surprising.

  • [az]* is any number of characters that are between a and z (ie any number of lowercase letters). This will match, assuming it's not quoted.

I finally figured it out, and why it was working so oddly

[az]* and [9]* and [anythinghere]* they all match because it matches zero or more times. so "direcheck" has [9] zero or more times.

so

 if [[ "$fname" =~ $FIND ]]; then

or

 if [[ $fname =~ $FIND ]]; then

are both correct, and

if [[ "$fname" =~ "$FIND" ]]; then

matches only when the string matches exactly because $FIND is matched as a literal string not regex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM