在每行的开头添加空格数(在一个字符串内)

时间:2011-11-03 23:01:48

标签: regex perl

这是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就可以做同样的事情。不幸的是,我还没有实现这一目标。 (很有可能,我认为太复杂了。)

那么,这个问题有什么可能性呢? 谢谢你的回答。

2 个答案:

答案 0 :(得分:5)

匹配每行的开头,或许:

$str =~ s/^/   /mg;

来自perlre的说明:

  • ^ - 匹配行的开头。
  • m - 将字符串视为多行,以便^$匹配行开头,并在字符串中的任何位置结束,而不仅仅是整个开头和结尾。
  • g - 全球 - 适用于找到的每场比赛。

答案 1 :(得分:0)

我认为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

相关问题