当我匹配并替换Perl中的几个单词时,如何保留空格?

sin*_*ish 1 regex perl substitution

假设我有一些原始文本:

here is some text that has a substring that I'm interested in embedded in it.

我需要文本匹配它的一部分,说:" has a substring".

但是,原始文本和匹配字符串可能存在空格差异.例如,匹配文本可能是:

has a
substring

要么

has  a substring

和/或原始文本可能是:

here is some
text that has
a substring that I'm interested in embedded in it.

我需要我的程序输出的是:

here is some text that [match starts here]has a substring[match ends here] that I'm interested in embedded in it.

我还需要保留原始的空白模式,只需添加开始和结束标记即可.

关于使用Perl正则表达式来实现这一点的任何想法?我试过了,但最终变得非常困惑.

Dav*_*res 5

自从我使用perl正则表达式以来已经过了一段时间,但是:

$match = s/(has\s+a\s+substring)/[$1]/ig
Run Code Online (Sandbox Code Playgroud)

这将捕获单词之间的零个或多个空格和换行符.它将用括号包围整个匹配,同时保持原始分隔.它不是自动的,但确实有效.

你可以用这个玩游戏,比如拿绳子"has a substring"并对它进行改造,使它变得"has\s*a\s*substring"不那么痛苦.

编辑:合并ysth的评论,\ s元字符匹配换行符和hobbs更正我的用法.