4

What are the semantics of * at the beginning of a RE? It is documented (man 7 regex) that for basic REs it matches only * (i.e., it turns to an ordinary character), but what happens for extended REs? By examples, it looks like it has the same semantics of '.*', but I cannot find any source for this.

prompt> echo "hello" | grep -E  '*'
hello
prompt> echo "hello" | grep  '*'
prompt> 
0

3 Answers 3

8

As far as the standard is concerned, the results are undefined:

*+?{

The <asterisk>, <plus-sign>, <question-mark>, and <left-brace> shall be special except when used in a bracket expression (see RE Bracket Expression). Any of the following uses produce undefined results:

  • If these characters appear first in an ERE, or immediately following a <vertical-line>, <circumflex>, or <left-parenthesis>
  • If a <left-brace> is not part of a valid interval expression (see EREs Matching Multiple Characters)

Any attempt to consistently explain what happens in this case would be at the mercy of the implementation. Going by @kos's answer, they probably match the empty regular expression.

0
5

Notice that echo "hello" | grep -E '*' returns hello because the string is a match and grep returns the whole line, not because * is the same as .*. You should test with -Eo:

% echo "hello" | grep -Eo '*' 
% 

I don't have sources to backup this, but a not too wild guess based on a pratical test suggests that a sequence of quantifiers at the beginning of the regex is just ignored:

% echo "*hello" | grep -Eo '*'    
% echo "+hello" | grep -Eo '+'
% echo "?hello" | grep -Eo '?'
% echo "{1}hello" | grep -Eo '{1}'
1}
% echo "***hello" | grep -Eo '***' 
% echo "*+?{1}hello" | grep -Eo '*+?{1}hello'
1}hello

My prompt prepends the return value at the start of the line in case of a return value different from 0, so those are all matches.

0
1

The grep -E 'regex' show lines containing the matching regex and highlights the matches in red color.

taking this into consideration, grep -E '*' will show all the lines with zero or more '(nothing)' in it.

grep '*' will just show lines having the star in it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .