Optional Group Expression

2019-09-16 15:07发布

问题:

Today I was working with regular expressions at work and during some experimentation I noticed that a regex such as (\w|) compiled. This seems to be an optional group but looking online didn't yield any results.

Is there any practical use of having a group that matches something, but otherwise can match anything? What's the difference between that and (\w|.*)? Thanks.

回答1:

(\w|) is a verbose way of writing \w?, which checks for \w first, then empty string.

I remove the capturing group, since it seems that () is used for grouping property only. If you actually need the capturing group, then (\w?).

On the same vein, (|\w) is a verbose way of writing \w??, which tries for empty string first, before trying for \w.


(\w|.*) is a different regex altogether. It tries to match (in that order) one word character \w, or 0 or more of any character (except line terminators) .*.

I can't imagine how this regex fragment would be useful, though.