tags:

views:

49

answers:

2

How can I catch an arbitrary string between defined words using regular expressions in .Net, e.g. @”…DEFINED_WORD1 some_arbitrary_string DEFINED_WORD2…”? Unfortunately my experiments with “(?=)” and other patterns are unsuccessful :(

+3  A: 

This will catch anything between the words, as long as there's a space after the first word and before the second. If there are multiple occurrences of WORD2 after WORD1, the first one will be considered.

WORD1 (.*?) WORD2

This is the same, but doesn't require spaces (e.g. "WORD1, some string WORD2" will match):

WORD1\b(.*?)\bWORD2

This will start from the first WORD1 and go on until the last WORD2:

WORD1\b(.*)\bWORD2

Depending on the details of your case, this may be cleaner and easier without regular expressions.

Max Shawabkeh
@digEmAll: Only the last Regex will do this. The first two use lazy matching to return only "xxx" for the first match.
Jens
@digEmAll: There are 3 regexes in this post, each of which specifies how it matches. The first two would return `xxx` and `yyy` (with/without spaces) while the last one would return `xxx WORD2 WORD1 yyy`, which is clearly explained in the post.
Max Shawabkeh
Yes sorry, I've looked in a hurry I didn't notice the "?" ;) Comment deleted
digEmAll
+2  A: 
"A(.*?)Z"

This would capture strings between "A" and "Z" into group 1.

See also

polygenelubricants