python - 使用 python re 转换字符串

标签 python regex

我得到一条字符串:

>>> 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/

相关文章:

python - pandas 一个热编码数据的每种列组合的行数

Python 正则表达式异常

java 正则表达式检测\n

python - 将内联注释移动到上一行

python - 裁剪圆面积的几何估计

python - 循环列表时的累积加法

java - 通过标签java分割字符串

regex - 如何检测正则表达式中 'end of string' 之前不存在的内容

python - Flask - 服务器无法启动

python - 找不到匹配的版本