正则表达式查找两行之间所有出现的特定字符串

时间:2013-07-22 12:22:08

标签: regex

我想搜索两行之间所有出现的特定字符串,例如

some line nobody is interested in
this is the beginning
this is of no interest
attention
not interesting
this is the ending

正则表达式如何在“这是开始”和“这是结局”之间找到“关注”?有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:2)

尝试此正则表达式的第1组:

(?s)this is the beginning.*?(attention).*?this is the ending

仅供参考(?s)启用“点匹配换行符”

答案 1 :(得分:0)

"=="兑换为您需要匹配的任何模式

bool foundStart = false;
for line in lines{
    if (line == "this is the beginning")
        foundstart = true;
    else if(line == "this is the ending")
        foundstart = false; //set to false if could come beginning again
        break; //or break directly
    else if (foundstart && line == interestingpattern)
        interesting_lines.Add(line);
}

或者像这样的正则表达式,如果你只需要一个“有趣”的出现:

re1='.*?'   # Non-greedy match on filler
re2='(start)'   # Word 1   //exchange to your pattern for start
re3='.*?'   # Non-greedy match on filler
re4='(interesting)' # Word 2 / Exchange to your pattern for interesting
re5='.*?'   # Non-greedy match on filler
re6='(end)' # Word 3 // exchange to your ending pattern

然后编译(re1+re2+re3+re4+re5+re6)并仅取出re4

答案 2 :(得分:0)

试试这个

var test = "some line nobody is interested in this is the beginning this is of no interest attention not interesting this is the ending";

var testRE = (test.match("this is the beginning (.*) this is the endin"));
alert(testRE[1].match(/attention/g).length);