正则表达式匹配两个字符串之间的所有字符 [英] Regex Match all characters between two strings

查看:75
本文介绍了正则表达式匹配两个字符串之间的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:这只是\na简单的句子".

Example: "This is just\na simple sentence".

我想匹配This is"和sentence"之间的每个字符.应该忽略换行符.我不知道正确的语法.

I want to match every character between "This is" and "sentence". Line breaks should be ignored. I can't figure out the correct syntax.

推荐答案

例如

(?<=This is)(.*)(?=sentence)

Regexr

我使用了后视 (?<=) 和前视 (?=) 以便匹配中不包含This is"和sentence",但这取决于您的用例,您也可以简单地编写 This is(.*)sentence.

I used lookbehind (?<=) and look ahead (?=) so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write This is(.*)sentence.

这里重要的是您激活正则表达式引擎的dotall"模式,以便 . 与换行符匹配.但是你如何做到这一点取决于你的正则表达式引擎.

The important thing here is that you activate the "dotall" mode of your regex engine, so that the . is matching the newline. But how you do this depends on your regex engine.

接下来是使用 .* 还是 .*?.第一个是贪婪的,将匹配到字符串中的最后一个句子",第二个是惰性的,将匹配到字符串中的下一个句子".

The next thing is if you use .* or .*?. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.

更新

正则表达式

This is(?s)(.*)sentence

(?s) 打开 dotall 修饰符的位置,使 . 匹配换行符.

Where the (?s) turns on the dotall modifier, making the . matching the newline characters.

更新 2:

(?<=is \()(.*?)(?=\s*\))

匹配您的示例这是(一个简单的)句子".在 Regexr

is matching your example "This is (a simple) sentence". See here on Regexr

这篇关于正则表达式匹配两个字符串之间的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆