正则表达式匹配两个字符串之间的所有字符

编程入门 行业动态 更新时间:2024-10-23 22:27:57
本文介绍了正则表达式匹配两个字符串之间的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

示例:这只是\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

更多推荐

正则表达式匹配两个字符串之间的所有字符

本文发布于:2023-10-23 13:48:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521001.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   两个   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!