python-3.x - 正则表达式用于在 Python 中检测模式并从该模式中删除空格

标签 python-3.x regex text

我有一个文件,其中包含形成以下格式的单词的段 <+segment1 segment2 segment3 segment4+> ,我想要的是一个输出,其中所有段彼此相邻以形成一个单词(所以基本上我想删除段之间的空格以及段周围的 <+ +> 符号)。例如:

输入:

<+play ing+> <+game s .+>

输出:

playing games. 

我首先尝试使用 \<\+(.*?)\+\> 检测模式但我似乎不知道如何删除空格

最佳答案

使用这个 Python code :

import re
line = '<+play ing+> <+game s .+>'
line = re.sub(r'<\+\s*(.*?)\s*\+>', lambda z: z.group(1).replace(" ", ""), line)
print(line)

结果:玩游戏。

lambda 还会删除空格。

正则表达式说明

--------------------------------------------------------------------------------
  <                        '<'
--------------------------------------------------------------------------------
  \+                       '+'
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \+                       '+'
--------------------------------------------------------------------------------
  >                        '>'

关于python-3.x - 正则表达式用于在 Python 中检测模式并从该模式中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70585999/

相关文章:

python - 删除匹配分隔符之间的单词/行

php - 以任意顺序匹配子模式

java - 将字符串 ["Scenario 1", "Scenario 2"] 转换为数组

python-3.x - Docker、Ubuntu 18.04 python3.7.2 : standard_init_linux. go:207: exec 用户进程导致 "exec format error"

django - RuntimeError : Model class xxx doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

python - Python 中 with 语句中的 file.close() 异常处理

java - 从文本文件初始化对象数组

python-3.x - 将图像的一部分叠加到另一幅图像上

"timer"句型的正则捕获组

Android 文本显示 - Canvas.drawText() 输出像素化