我得到一条字符串:
>>> 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
我尝试了 python re 模块,并写了这样的内容:
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
。谁能指出我哪里错了?
最佳答案
\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
关于python - 使用 python re 转换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8389593/