Clarity on how can `.*` match all strings?

44 views Asked by At

I guess this is silly question, but I am confused as to how can regex .* match all the strings?
*: zero or more occurrences of the preceding element,
.: matches any one character,

So, in .*, . should match any one character( say 'x'), then * would mean 0 or more occurrences of 'x', thus giving us strings like:
"",
"x",
"xx",
"xxx",
"xxxxxxx",.. etc.

But how is it able to match any random string like "ab12b3v34"?
Shouldn't this be actually the case for [.*]*?

What am i missing here please explain.

1

There are 1 answers

0
Insouciant On

My confusion was due to my ignorance of order of evaluation.
I thought the evaluation went as follows(which is wrong):

  1. In .*, . is evaluated first, say . is replaced by 'x'. Here 'x' is just a literal character.
  2. Then x* would be evaluated leading to strings like "", "x", "xx", "xxx", ...etc.
  3. Thus my doubt as to how it produced strings like "ab12b3v34".

But the correct order of evaluation is:

  1. In .*, * is evaluated first, thus resulting in another regex pattern like , ., .., ..., ...etc, where . are still wildcards.
  2. Then the wildcard . is/are replaced by any character, thus resulting in string(without new-line character) such as "ab12b3v34"(in this case from .........).

Thanks to all who commented for your patience.