How to find a word before a string match

to questions, but did not get the right answer. I need a separate Regex for before and after the corresponding line.

1) Find a word After a certain phrase / word (this one works fine)

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

2) Find a word Before a certain phrase / word (does not work)

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

MyText = "XYZ"

Input = "this is abc xyz defg"

the conclusion should be like

1) for the first one that works xyz defg

2) the second that does not work

abc xyz

+4
source share
2 answers

You need to resolve the space between the word before and the keyword.

, Regex.Escape mytext.

,

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

, , ( word , \b):

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

/

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

/

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

Source: https://habr.com/ru/post/1608485/


All Articles