繁体   English   中英

正则表达式检测模式并从 Python 中的模式中删除空格

[英]Regex to detect pattern and remove spaces from that pattern in Python

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

输入:

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

Output:

playing games. 

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

使用此Python 代码

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

结果playing games.

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 代码

这个表达式可以分解如下。

<\+     # Match '<+'
|       # or
\+>     # Match '<+'
|       # or
(?<!>)  # Negative lookbehind asserts current location is not preceded by '>'
[ ]     # Match a space
|       # or
[ ]     # Match a space
(?!<)   # Negative lookahead asserts current location is not followed by '<'

我已将每个空格放在上面的字符 class 中,因此它是可见的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM