Need Regex Help to Get Words Before and After a Regex Match

Answer for Words Before and After.docx (16.5 KB)

Good evening UiPath Forum,

I have a use case that involves a step that requires a regex match. I need to match a text value and then get X words before it and X words after it. In searching thus far, Forum posts don’t address this specifically. My searches have been via the Edge browser which returns the Edge chat results along with Edge search results. The full response is attached. It reflects this as a solution. This example is for 3 words before and 3 words after a match.


I am not able to get this to work in a standard ASSIGN activity like System.Text.RegularExpressions.Regex.Matches(…).
I would greatly appreciate the feedback of someone who can provide a UiPath syntax for getting X words before and X words after a match.

Most appreciated.


Can you try the following sample?

m = System.Text.RegularExpressions.Regex.Match(strData,"(?<BEFORE>(\S+\s+){1,3})target(?<AFTER>(\s+\S+){1,3})")

note: target keyword is “target” and n =3

Sample (2.6 KB)


Hi @jamiejam ,
Thanks for reaching out to UiPath community.

Try using this regex pattern ,

Here, replace “YourMatchText” with the text you’re looking for, and " {3}"represents the number of words you want before and after.


Thanks VERY much Pratik. You responded with a post that was also a solution but for some reason I can’t mark both as a solution. I very much appreciate your support on this issue.

One more question Yoichi if you don’t mind. This worked perfectly to populate the MATCH variable. m = System.Text.RegularExpressions.Regex.Match(strData,“(?(\S+\s+){1,3})target(?(\s+\S+){1,3})”)

The value ‘target’ above is a specific string value. To implement this match, I will pass a variable into that string where ‘target’ is. I am having trouble updating the ASSIGN activity to use a variable there. I get this error.

My activity looks like this. I am using the menu on the expression editor to put a string variable in that spot where ‘target’ was.

How to I get a string variable in there instead of a specific string value?
Thanks again.

Add quotation marks " and a plus + to each side of ‘strToMatch’

Like this:


It may be better to use the following expression if there is possibility to contains regex special character in strToMatch



Hi @jamiejam ,
No problem man, the good thing is UiPath Community got you a solution.
Cheers mate.!!

Excellent Steven… Quotes turned out to be the clearest way. Thanks very much for that.

Thanks again Yoichi. I used that directly and it worked.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.