Civa
Civa

Reputation: 2176

Small confusion in regex at | (pipe)

when i use pattren

"(see|see also) [\w\d]+"

on Text

see page 
see also page

But output Matches is

see page 
see also

if im interchanged see, see also

"(see also|see) [\w\d]+"

the output is

see page 
see also page

I thought both are same. May i know why this is happen?

Upvotes: 1

Views: 37

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

Removing the alternation and leaving see [\w\d]+ will match the string "see also page" because it is satisfied by see also. The way that regular expressions work with alternation (at least in this case) is that it will attempt to match each option in order with the rest of the pattern and stop as soon as it does so successfully, or go back to the alternatives when it fails. When you reverse the alternation, it tries to match with see also first, but that will fail with "see page."

It would make more sense to write this as see( also)? [\w\d]+

Upvotes: 6

Related Questions