【问题标题】:Add number of white spaces at begin of each line (within one string)在每一行的开头添加空格数(在一个字符串内)
【发布时间】:2011-11-04 07:20:47
【问题描述】:

这是Perl: add character to begin of a line 的后续问题。

情况
在现有的 Perl 脚本中,我有一个合理的长字符串 $str,其中包含未知数量的换行符 (\n)。现在字符串末尾有换行符。

$str = "Hello\nWorld.\nHow is it going?"

问题
我想在字符串中每行的开头添加一定数量的(恒定)空格:(在本例中为 3)

$str = "   Hello\n   World.\n   How is it going?"

第一种方法 我的第一种方法是以下 RegEx

$str =~ s/(.*?\n)/   \1/g;

并缓存最后一行,不被新行终止

$str =~ s/(.*)\n(.*)?$/\1\n   \2/g;

愿望
第一的。以上几行完美地工作,完全符合我的意图。但。我知道,RegEx 很强大,因此我很确定,一个人可以在短短的 RegEx 中做同样的事情。不幸的是,我还没有做到这一点。 (很可能,我的想法太复杂了。)

那么,这个问题有哪些可能性呢?
感谢您的任何回答。

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    匹配每一行的开头,也许:

    $str =~ s/^/   /mg;
    

    来自perlre的笔记:

    • ^ - 匹配一行的开头。
    • m - 将字符串处理多行,以便 ^ 和 $ 匹配字符串中任何位置的行开始和结束,而不仅仅是整体的开始和结束。
    • g - 全局 - 适用于找到的每个匹配项。

    【讨论】:

    • 非常感谢。标志m 是丢失的关键。上面未说明的附加问题:是否有多个空格的缩写?我不想输入(或硬编码)5 个或更多空格。
    • @T.K. - 你可以这样做:my $indent = ' ' x 5; $str =~ s/^/$indent/mg; 这将为$indent 分配五个空格并将其用于替换。
    • 这是一种选择,是的。但是不能使用正则表达式的“乘数”:{n}吗?
    【解决方案2】:

    我认为 OP 意味着换行符是字符串的一部分?如果是这种情况,那么这个正则表达式:

    $subject =~ s/((?<=^)|(?<=\\n))/    /g;
    

    应该可以。

    解释:

    "
    (              # Match the regular expression below and capture its match into backreference number 1
                      # Match either the regular expression below (attempting the next alternative only if this one fails)
          (?<=           # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
             ^              # Assert position at the beginning of the string
          )
       |              # Or match regular expression number 2 below (the entire group fails if this one fails to match)
          (?<=           # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
             \\n             # Match a line feed character
          )
    )
    "
    

    看到它工作here。

    【讨论】:

    • 这是有线的。在我的脚本中,这不起作用。它只在整个字符串的开头添加空格,而不是在每个换行符之后。
    • @T.K.那么你看到它工作正常吗? :) 所以我的意思是如果你只是复制它应该可以工作。我不知道你的情况有什么问题:)
    猜你喜欢
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多