The asterisk in regex


 
Thread Tools Search this Thread
# 1  
The asterisk in regex

I know through (my very limited) experience that you can't use the asterisk alone in a regex, but I still don't quite understand why. After all, it should match 'any or no characters'. To my mind, '*grep' should match:

grep
egrep
fgrep

While '.*grep' should match

egrep
fgrep

...but not 'grep' because it seems like we are insisting upon a character in front of 'grep' with that dot. Yet that is clearly not the case. Can someone explain why this is so?
(Hope my use of 'grep' as the search term doesn't cause any confusion)
# 2  
It is a little bit different:

Code:
$ printf "grep\nfgrep\negrep\n" | grep '*grep'
$ printf "grep\nfgrep\negrep\n" | grep '.*grep'
grep
fgrep
egrep
$ printf "grep\nfgrep\negrep\n" | grep '..*grep'
fgrep
egrep
$ printf "*grep\ngrep\nfgrep\negrep\n" | grep '*grep'
*grep

# 3  
Quote:
Originally Posted by sudon't
I know through (my very limited) experience that you can't use the asterisk alone in a regex, but I still don't quite understand why. After all, it should match 'any or no characters'.
Zero or more what, is the question. * is a modifier that changes the character before it. You may be used to globs, where * exists by itself and needs no specifier in front of it because it always matches everything. Regexes are not that.

. is a special character that means "anything".

"A*" on the other hand would match "", "A", "AA", "AAAAAAAAAA" and so forth.

"[0-9]*" would match "0123", etc.
This User Gave Thanks to Corona688 For This Post:
# 4  
OK, I get it. Same with the question mark.
 

Previous Thread | Next Thread
Thread Tools Search this Thread
Search this Thread:
Advanced Search

Featured Tech Videos