Perl 忽略正则表达式替换的替换侧的空格

发布于 2024-12-03 06:35:40 字数 369 浏览 5 评论 0原文

假设我有 $str = "onetwo"

我想编写一个忽略空格的 reg ex 替换命令(这使其更具可读性):

$str =~ s/
          one
          two
         /
          three
          four
         /x

这会生成 "\n Three\nfour\n" ,而不是 "thirdfour" > (其中 \n 是换行符)。基本上, /x 选项会忽略替换匹配侧的空格,但不会忽略替换侧的空格。如何也忽略替换侧的空格?

Suppose I have $str = "onetwo".

I would like to write a reg ex substitution command that ignores whitespace (which makes it more readable):

$str =~ s/
          one
          two
         /
          three
          four
         /x

Instead of "threefour", this produces "\nthree\nfour\n" (where \n is a newline). Basically the /x option ignores whitespace for the matching side of the substitution but not the replacement side. How can I ignore whitespace on the replacement side as well?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

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

评论(1

瑶笙 2024-12-10 06:35:40

s{...}{...} 基本上是 s{...}{qq{...}}e。如果您不需要 qq{...},则需要将其替换为其他内容。

s/
   one
   two
/
   'three' .
   'four'
/ex

甚至:

s/
   one
   two
/
   clean('
      three
      four
   ')
/ex

clean 的可能实现:

sub clean {
    my ($s) = @_;
    $s =~ s/^[ \t]+//mg;
    $s =~ s/^\s+//;
    $s =~ s/\s+\z//;
    return $s;
}

s{...}{...} is basically s{...}{qq{...}}e. If you don't want qq{...}, you'll need to replace it with something else.

s/
   one
   two
/
   'three' .
   'four'
/ex

Or even:

s/
   one
   two
/
   clean('
      three
      four
   ')
/ex

A possible implementation of clean:

sub clean {
    my ($s) = @_;
    $s =~ s/^[ \t]+//mg;
    $s =~ s/^\s+//;
    $s =~ s/\s+\z//;
    return $s;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文