忽略正则表达式中的空格

时间:2016-02-26 14:42:14

标签: python regex

我想忽略空格并解析像(int, int) xx (int, int)这样的模式。例如,

import re
m = re.match(r"[\s]*\([\s]*(\d+)[\s]*,[\s]*(\d+)[\s]*\)[\s]*xx[\s]*\([\s]*(\d+)[\s]*,[\s]*(\d+)[\s]*\)[\s]*", "   (2,  74) xx   (5  ,6), physicist")
print (m.group(0)) #    (2,  74) xx   (5  ,6)
print (m.group(1)) # 2
print (m.group(2)) # 74
print (m.group(3)) # 5
print (m.group(4)) # 6

正如您所看到的,在我的模式中,有许多[\s]*代表零个或多个空格。有没有更简单的方法来编写这种模式?

4 个答案:

答案 0 :(得分:5)

我不知道正则表达式中的方法,但最简单的解决方案是使用简单的字符串替换:

import re
m = re.match(r"\((\d+),(\d+)\)xx\((\d+),(\d+)\)", "   (2,  74) xx   (5  ,6), physicist".replace(' ', ''))
print (m.group(0)) # (2,74)xx(5,6)
print (m.group(1)) # 2
print (m.group(2)) # 74
print (m.group(3)) # 5
print (m.group(4)) # 6

您还可以使用正则表达式删除任何类型的空格(而不仅仅是空格):

import re
s = re.sub(r'\s+', '', '   (2,  74) xx   (5  ,6), physicist')
m = re.match(r"\((\d+),(\d+)\)xx\((\d+),(\d+)\)", s)
print (m.group(0)) # (2,74)xx(5,6)
print (m.group(1)) # 2
print (m.group(2)) # 74
print (m.group(3)) # 5
print (m.group(4)) # 6

答案 1 :(得分:3)

直接答案是。即使它们只是白色空间,但事实是它们都是人物,因此,它们是模式的一部分。我认为这里有一些方法

  1. 通过删除不需要的空格来预处理字符串。
  2. 找到表达模式的另一种方式。
  3. 使用其他方法进行匹配。
  4. e.g。

    guard

答案 2 :(得分:2)

如果您想简化特定模式,您可以在之前的一个单独步骤中消除所有空格,因为它们与您的模式无关。

示例:

import re
input = '   (2,  74) xx   (5  ,6), physicist'
m = re.match(r"\((\d+),(\d+)\)xx\((\d+),(\d+)\)", input.replace(' ', '')

答案 3 :(得分:2)

我认为你想要的只是获得所有4个整数,所以你可以删除所有空格然后匹配

import re
a = '(  2 , 74 ) xx (5       , 6 )'
b = re.sub(r'\s+','',a)
m = re.match(r'\((\d+),(\d+)\)xx\((\d+),(\d+)\)',b)
print (m.group(0)) # (2,74)xx(5,6)
print (m.group(1)) # 2
print (m.group(2)) # 74
print (m.group(3)) # 5
print (m.group(4)) # 6
相关问题