简体   繁体   中英

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 (ie, 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM