I'm trying to create a Regex expression in vb.net that includes the search term in the result (or have some way of finding which term was found).
For example, with these 2 sentences:
hello Sailor my name is Bill
hello Soldier my name is Bill
I can use this expression to look for either 'Sailor' or 'Soldier':
(?<=Sailor |Soldier ). ?(?= Bill)
... and this gives me:
my name is
Which is the result I want, but I also need to know whether it matched on 'Sailor' or 'Soldier'. Is there a way to do this?
Thanks!
CodePudding user response:
Sorry, found it when I did some tinkering. I just need this expression:
(?=Sailor |Soldier ). ?(?= Bill)
i.e. drop the < symbol from the start term.
CodePudding user response:
It is not necessary to first assert Sailor
and Soldier
using a lookahead and then matching them.
You can match them immediately, and perhaps add some word boundaries to prevent partial word matches:
\b(?:Sailor|Soldier) . ?(?= Bill)\b