2011-11-03 110 views
3

这是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就可以做同样的事情。不幸的是,我还无法做到这一点。 (这很有可能,我想太复杂了。)

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

回答

4

匹配的开始每行的代替,或许:从perlre

$str =~ s/^/ /mg; 

注:

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

非常感谢。标志'm'是失踪的钥匙。以上未提及的其他问题:是否有多个空格的缩写?我不想输入(或硬编码)5个或更多空格。 –

+0

@ T.K。 - 你可以这样做:'my $ indent =''x 5; $ str =〜s/^/$ indent/mg;'这将为'$ indent'分配五个空格并将其用于替换。 –

+0

这将是一种选择,是的。但是不可能使用RegEx的“乘法器”:'{n}'? –

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

+0

这是有线的。在我的脚本中这是行不通的。它只在整个字符串的最开始处添加空格,但不在每个换行符后面。 –

+0

@ T.K。那么你看到它的工作正确吗? :)所以我的意思是如果你只是复制它应该工作。我不知道你的情况有什么问题:) – FailedDev

相关问题