简体   繁体   English

正则表达式在字符串中的任何特定单词之前和之后查找特定单词

[英]regex to find a specific word before and after any specific word in string

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正则表达式应该给我一个字符串,其中包含开始词是click结束词是end搜索词是MyUrl.com

Here, in this case, the output of the above string would be,在这种情况下,上述字符串的 output 将是,

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)?\S MyUrl.com\S (?:\s\S+)? (?:\S+\s)?\S MyUrl.com\S (?:\s\S+)? -> Output is URL MyUrl.com click -> Output 是URL MyUrl.com 点击

I couldn't find the proper regex for my requirement.我找不到适合我要求的正则表达式。

These parts (?:\S+\s)?这些部分(?:\S+\s)? and (?:\s\S+)?(?:\s\S+)? match 0 or 1 time in the pattern due to the ?由于?在模式中匹配 0 次或 1 次

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.您必须指定起始词和结束词,并将匹配空白字符和非空白字符的部分重复 0 次或多次以匹配其间的所有词。

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

Regex demo正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM