huda
huda

Reputation: 4297

How to find a word before matching string

through to stack-overflow questions but didn't get the proper answer. I need a separate Regex for before & after a matching string.

1) Find word After a specific phrase/word (this one working fine)

  var regex = new Regex(@"(?:" + mytext + @"\s)(?<word>\b\S+\b)");

2) Find word Before a specific phrase/word (not working)

 var regex = new Regex(@"(?:\S+\s)?\S*" + mytext  + @"\b\S");

mytext="xyz"

Input="this is abc xyz defg"

output should be like that

1) for first,which is working
xyz defg

2) second, which is not working

abc xyz

Upvotes: 5

Views: 1816

Answers (2)

qqus
qqus

Reputation: 493

Find word After a specific phrase/word

var regex = new Regex(mytext + @"\s\w+");

Find word Before a specific phrase/word

var regex2 = new Regex(@"\w+\s" + mytext);

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627488

You need to allow the whitespace between the word before and the keyword.

Also, for additional safety, I'd use a Regex.Escape with the mytext variable.

So, I suggest using

var regex = new Regex(@"(?<word>\b\S+\b\s+)?(?:" + Regex.Escape(mytext) + @"\b)");

See demo

And to make sure we capture a whole word, you can use the following variation of the regex (since the word is optional, \b might be necessary):

var regex = new Regex(@"(?<word>\b\S+\b\s+)?(?:\b" + Regex.Escape(mytext) + @"\b)");
                                               ^^

Upvotes: 2

Related Questions