简体   繁体   English

Select 特定 两个字符串之间的文本(多行)

[英]Select specific Text between two strings (multiline)

I want to Select specific text between two strings using regex.我想使用正则表达式在两个字符串之间 Select 特定文本。

eg:例如:

 foo I have four toys bar //single line foo //multiline I have four toys bar foo I have three pets bar foo I have three pets bar

How to select text between "foo" and "bar" with specific word containing "four"如何 select 在“foo”和“bar”之间使用包含“四”的特定单词的文本

Output: Output:

 I have four toys I have four toys

My code:我的代码:

 foo[\s\S]*?(four)[\s\S]*?bar

My code is working fine but problem is that when when "four" word does not comes between "foo" and "bar" it is selecting all text till "four" word我的代码运行良好,但问题是当“foo”和“bar”之间没有出现“四个”字时,它会选择所有文本直到“四个”字

foo I have three pets bar foo I have four toys bar foo I have three pets bar

I just want text between "foo" and "bar" when it is containg specific word "four"当包含特定单词“four”时,我只想要“foo”和“bar”之间的文本

We can use the following regex pattern, in dot all mode:我们可以在全点模式下使用以下正则表达式模式:

 \bfoo\s+(?:(?.\bbar\b)?)*?\s+four\s+(:?(.?\bfoo\b) )* \s+bar

 var input = `foo I have four toys bar foo I have four toys bar foo I have three pets bar foo I have three pets bar`; var matches = input.match(/\bfoo\s+(?:(?.\bbar\b)?)*?\s+four\s+(:?(.?\bfoo\b).)*.\s+bar/gs),map(x => x;replace(/^foo\s+|\s+bar$/g. "")); console log(matches)

An explanation to this complex regex pattern might be helpful here:对这种复杂的正则表达式模式的解释在这里可能会有所帮助:

 \bfoo\s+ match 'foo' followed by one or more whitespace characters (?:(?.\bbar\b)?)*? match any content WITHOUT encountering 'bar' \s+four\s+ match 'four' surrounded by whitespace (:?(.?\bfoo\b) )* match any content WITHOUT encountering 'foo' \s+bar whitespace followed by ending 'bar'

Note that due to the way match() behaves, we also have a map step where we strip off leading foo and ending bar from every match.请注意,由于match()的行为方式,我们还有一个map步骤,我们从每场比赛中去除前导foo和结束bar

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

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