n7rider
n7rider

Reputation: 487

Regex to get the word next to all of the given words

I need a regex to capture the word immediately next to all of the words I provide.

Example Sentence:

user="panda" is trying to access resource="system"

Words to be captured: panda & system (i.e., the word immediately next to the words 'user' & 'resource')

Currently, I use this regex (?<=name=\")(.*?)(?=\";) which returns the name 'panda'. I'm looking for a query that would capture both the user and the resource in the above sentence.

Can someone help with the regex query to do this?

Upvotes: 0

Views: 40

Answers (2)

41686d6564
41686d6564

Reputation: 19651

Since .NET's regex supports non-fixed length Lookbehinds, you can just add all the words you want in a non-capturing group and use alternation:

(?<=(?:user|resource)=\").*?(?=\")

Demo.

You can also get rid of the Lookahead by using something like this:

(?<=(?:user|resource)=\")[^"]*

Demo #2

Upvotes: 1

Adassko
Adassko

Reputation: 5343

just a simple regex with lazy matching should do the job

user="(.*?)".*resource="(.*?)"

it gets more complicated if you need to match more than two words in any order, I wouldn't use a RegEx in this case at all, you would rather want to make a lexer for that. Just make a class/procedure that will tokenize the sentence first, then parser to get the information you want

Upvotes: 1

Related Questions