2011-11-03 108 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

相關問題