Python regex:具有多个空格的纯文本文件,但我想仅保留一个空格的名称

问题描述 投票:1回答:3

我有几行这样的内容:

00000     SomeText    00000    0000
00000     Some'Text    00000    0000
1111     Some Text Text    33    4444

目前,我正在使用:

match = re.search(r'(\d+)\s+([\w@._]+)\s+(\d+)\s+(\d+)', line)

但是我缺少所有的“某些文本”和“某些文本”。

在每个列之间,有2个以上的空格。

我想抓住:-第一位数字-文字只有一个空格-第二位数-第三位数

非常感谢!

python regex whitespace
3个回答
1
投票

您可以使用

(\d+)\s+(\S+(?:\s\S+)*)\s+(\d+)\s+(\d+)

或者,如果这些是整行/字符串(如果您需要处理单个多行文本,则可能需要re.MULTILINEre.M选项和[^\S\r\n]+而不是\s+

^(\d+)\s+(\S+(?:\s\S+)*)\s+(\d+)\s+(\d+)$

请参见regex demo

这里的重点是\S+(?:\s\S+)*

  • \S+-1+非空格
  • (?:\s\S+)*-零个或多个序列
    • \s-空格
    • \S+-1+非空格

0
投票

只需将所有\s+替换为\s{2,},然后将\s添加到第二个列组:

match = re.search(r'(\d+)\s{2,}([\w@._\s]+?)\s{2,}(\d+)\s{2,}(\d+)', line)

另一种选择是使用re.split代替re.search

columns = re.split(r'\s{2,}', line)

0
投票

而不是相当长的正则表达式,我建议分割\s{2,}上的每一行并分别测试每一列

text = '''00000     SomeText    00000    0000
00000     Some'Text    00000    0000
1111     Some Text Text    33    4444'''

for line in text.split('\n'):
    c1, c2, c3, c4 = re.split(r'\s{2,}', line)
    if c1.isnumeric() and ('  ' not in c2) and \
       c3.isnumeric() and c4.isnumeric():
        print(line)
# prints:
00000,SomeText,00000,0000
00000,Some'Text,00000,0000
1111,Some Text Text,33,4444
© www.soinside.com 2019 - 2024. All rights reserved.