findall函数的python正则表达式问题

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

我正在尝试提出一个正则表达式来解析3x-5y + 5之类的方程,将其分为三部分。以下是代码。

它在前三种情况下都能正常工作,但对于最后而不是-3y,它只给出3y

为什么?

'''

  import re
  pattern = r"[-+]?\d*\.?\d*[a-z]?"

  print(re.findall(pattern, "4y-3x-6"))
  print(re.findall(pattern, "4x+3y-6"))
  print(re.findall(pattern, "-4x+3y-6"))
  print(re.findall(pattern, "4x−3y-6"))

'''

输出:

['4y','-3x','-6','']

[''4x','+ 3y','-6','']

['-4x','+ 3y','-6','']

[''4x','','3y','-6','']

python regex
1个回答
0
投票

字符串4x−3y-6中有错误。如果检查该字符串的十六进制代码,您会看到是连字符而不是减号。

> echo -n '4x−3y-6' | xxd
00000000: 3478 e288 9233 792d 36                   4x...3y-6

如您所见,其中有两个不同的信号。如果要同时使用和匹配它们,则应将正则表达式更改为:

  pattern = r"[-+−]?\d*\.?\d*[a-z]?"

© www.soinside.com 2019 - 2024. All rights reserved.