Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a word before matching string

Tags:

c#

regex

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

like image 828
huda Avatar asked Sep 22 '15 13:09

huda


1 Answers

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);
like image 176
qqus Avatar answered Oct 26 '22 16:10

qqus