Home > Blockchain >  regex to find a specific word before and after any specific word in string
regex to find a specific word before and after any specific word in string

Time:10-02

I need a regex that gives me the string with the specific words before and after any other specific word, including the search word itself.

Please Note: The start word and end word will not be the same word.

Example

string text = "strat text click my URL MyUrl.com click me end text completed"; 

The regex should give me a string that contains start word is click and end word is end and the search word is MyUrl.com

Here, in this case, the output of the above string would be,

click my URL MyUrl.com click me end

I tried with the following regex which returns the text having one word before and after the searched text

(?:\S \s)?\SMyUrl.com\S(?:\s\S )? -> Output is URL MyUrl.com click

I couldn't find the proper regex for my requirement.

CodePudding user response:

These parts (?:\S \s)? and (?:\s\S )? match 0 or 1 time in the pattern due to the ?

If you want to match all the words between the start and the end pattern, there should be more repetitions but you don't know how many there are in between.

You would have to specify the start and the end word, and repeat the part matching whitespace chars and non whitspace chars 0 or more times to match all the words in between.

\bclick(?:\s \S )*? \S*MyUrl\.com\S*(?:\s \S )*? end\b

Regex demo

  • Related