Anthony Calandra
Anthony Calandra

Reputation: 1528

Optional Group Expression

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.

Upvotes: 0

Views: 50

Answers (1)

nhahtdh
nhahtdh

Reputation: 56829

(\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.

Upvotes: 2

Related Questions