Regex to match everything between

huangapple go评论63阅读模式
英文:

Regex to match everything between

问题

我已经尝试了一个小时,但我不是正则表达式专家。我想做的事情似乎相当简单,但比我想象的要困难得多。

基本上我有这样的代码:

<<< Some code

    def prnt(string)
        print(string)
    end

=====

    def println(string)
        puts(string)
    end

*****
<<< Some more code
...

我想做的是捕获第一行<<< Some code*****之间的所有内容。文件中会有很多类似的块。

到目前为止,我使用的正则表达式是(?:<<< .*\r?\n)([\s\S]+)(?:[*]{5}),但它并不起作用。有什么想法吗?我使用的语言是Go。

英文:

I've been trying at this for an hour, but I'm no regexpert. What I want to do seems fairly simple, but it's turning out a lot more difficult than I would have thought.

Basically I have this:

&lt;&lt;&lt; Some code

    def prnt(string)
        print(string)
    end

=====

    def println(string)
        puts(string)
    end

*****
&lt;&lt;&lt; Some more code
...

What I want to do is capture everything between the first line &lt;&lt;&lt; Some code and the *****. There will be lots of blocks like this in a file.

The regex that I have so far is this (?:&lt;&lt;&lt; .*\r?\n)([\s\S]+)(?:[*]{5}), but it doesn't really work. Any ideas? The language I'm using it in is Go.

答案1

得分: 2

没关系,我弄明白了!

(?:&lt;&lt;&lt; .*\r?\n)([\s\S]*?)(?:[*]{5})

看起来关键是将中间的匹配组设为懒惰模式,这样它会尽可能少地匹配。

英文:

Never mind I figured it out!

(?:&lt;&lt;&lt; .*\r?\n)([\s\S]*?)(?:[*]{5})

It seems like the big thing was making the match group in the middle lazy so that it would match as little as possible.

答案2

得分: 0

这个正则表达式捕获了第一组中的目标,但你必须使用“点匹配换行符”开关“s”:

<<<[^\r\n]+[\r\n]*(.*?)[*]{5}

请参考在线演示

英文:

This captures the target in group 1, but you must use the "dot matches newline" switch "s":

&lt;&lt;&lt;[^\r\n]+[\r\n]*(.*?)[*]{5}

See live demo.

huangapple
  • 本文由 发表于 2016年2月6日 10:43:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/35236743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定