How can I remove linebreaks with a Perl regex?

How can I remove linebreaks with a Perl regex?

像你 发布于 2021-11-27 字数 315 浏览 1001 回复 2 原文

when I run:

perl -e '$x="abcnxyzn123"; $x =~ s/n.*/... multiline.../; printf("str %sn", $x);'

I expect result to be:

str abc... multiline...

instead I get

str abc... multiline...
123

Where am I going wrong?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不甘平庸 2022-06-07 2 楼

You need to use the 's' modifier on your regex, so that the dot '.' will match any subsequent newlines. So this:

$x =~ s/n.*/... multiline.../;

Becomes this:

$x =~ s/n.*/... multiline.../s;
迟月 2022-06-07 1 楼
$x =~ s/n.*/... multiline.../s

/s modifier tells Perl to treat the matched string as single-line, which causes . to match newlines. Ordinarily it doesn't, resulting in your observed behavior.