英文:
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:
<<< Some code
def prnt(string)
print(string)
end
=====
def println(string)
puts(string)
end
*****
<<< Some more code
...
What I want to do is capture everything between the first line <<< Some code
and the *****
. There will be lots of blocks like this in a file.
The regex that I have so far is this (?:<<< .*\r?\n)([\s\S]+)(?:[*]{5})
, but it doesn't really work. Any ideas? The language I'm using it in is Go.
答案1
得分: 2
没关系,我弄明白了!
(?:<<< .*\r?\n)([\s\S]*?)(?:[*]{5})
看起来关键是将中间的匹配组设为懒惰模式,这样它会尽可能少地匹配。
英文:
Never mind I figured it out!
(?:<<< .*\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":
<<<[^\r\n]+[\r\n]*(.*?)[*]{5}
See live demo.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论