2011-12-05 43 views
2

我得到一個字符串行:字符串與Python轉換重新

>>> line = " abc\n def\n\n ghi\n jkl" 
>>> print line 
    abc 
    def 

    ghi 
    jkl 

,我想將其轉換爲 「ABCDEF \ n \ n ghijkl」,如:

>>> print " abcdef\n\n ghijkl" 
    abcdef 

    ghijkl 

我試過蟒蛇重模塊,寫這樣的事:

re.sub('(?P<word1>[^\n\s])\n\s*(?P<word2>[^\n\s])', '\g<word1>\g<word2>', line) 

,但我得到這個:

>>> re.sub('(?P<word1>[^\n\s])\n\s*(?P<word2>[^\n\s])', '\g<word1>\g<word2>', line) 
Out: ' abcdefghijkl' 

在我看來,\n\s*部分也匹配\n\n。任何人都可以指出我錯在哪裏?

回答

4

\s匹配空格,\t,\n(並且,根據您的正則表達式引擎)還有其他一些空格字符。

所以,如果你只是想取代單換行+空格/製表符,你可以使用這個:

newline = re.sub(r"(?<!\n)\n[ \t]*(?!\n)", "", line) 

說明:

(?<!\n) # Assert that the previous character isn't a newline 
\n  # Match a newline 
[ \t]* # Match any number of spaces/tabs 
(?!\n) # Assert that the next character isn't a newline 

在Python:

>>> line = " abc\n def\n\n ghi\n jkl" 
>>> newline = re.sub(r"(?<!\n)\n[ \t]*(?!\n)", "", line) 
>>> print newline 
    abcdef 

    ghijkl 
0

試試這個,

line = " abc\n def\n\n ghi\n jkl" 
print re.sub(r'\n(?!\n)\s*', '', line) 

它給,

ABCDEF
ghijkl

它說, 「更換新線,其次是不與任何一個新行的空間。」

更新:這是一個更好的版本

>>> re.sub(r'([^\n])\n(?!\n)\s*', r'\1', line) 
' abcdef\n\n ghijkl' 

它給什麼你在第一個帖子裏說。

0

您可以簡化正則表達式,如果你使用\S,它匹配任何非空白字符:

>>> import re 
>>> line = " abc\n def\n\n ghi\n jkl" 
>>> print re.sub(r'(\S+)\n\s*(\S+)', r'\1\2', line) 
    abcdef 

    ghijkl 

可是,爲什麼自己的正則表達式不工作是因爲你的<word1><word2>組僅匹配的原因一個字符(即他們沒有使用+)。因此,通過這種簡單的校正,您的正則表達式將生成正確的輸出:

>>> print re.sub(r'(?P<word1>[^\n\s]+)\n\s*(?P<word2>[^\n\s]+)', r'\g<word1>\g<word2>', line) 
    abcdef 

    ghijkl