0
votes

Let's assume I have some text:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

  1. If I query for "sed do" I want to get "sed to" + additional 2 words on the left and on the right. In this case I want to get:

adipiscing elit, sed do eiusmod tempor

  1. If I query for "aliqua" I want to get:

dolore magna aliqua

etc

I believe the best way is to do it with Regex (it's not must-have), but I don't know how to construct such a query.

1
you can use if-else condition and two regexesrock321987

1 Answers

1
votes

This can be done by surrounding the target word with \s?\S*\s?\S*, like this:

\S*\s?\S*\s?consectetur\s?\S*\s?\S*

demo 1.

Since space \s is optional and \S* can match zero characters, this works on both ends of the text as well (demo 2, demo 3).

Note: This approach does not work too well when words are separated by multiple spaces, because it relies on counting whitespace.