为什么这些正则表达式不起作用?
Why are these regular expressions not working?
我想要一个正则表达式来匹配复杂的数学表达式。
但是我会要求一个更简单的正则表达式,因为这将是最简单的情况。
示例 输入:
1+2+3+4
我想分开每个字符:
[('1', '+', '2', '+', '3', '+', '4')]
有一个限制:必须至少有一个操作(即1+2
)。
我的正则表达式:([0-9]+)([+])([0-9]+)(([+])([0-9]+))*
或 (\d+)(\+)(\d+)((\+)(\d+))*
输出 re.findall('(\d+)(\+)(\d+)((\+)(\d+))*',"1+2+3+4")
:
[('1', '+', '2', '+4', '+', '4')]
为什么这不起作用? Python 是问题吗?
您需要 ([0-9]+)([+])([0-9]+)(?:([+])([0- 9]+))*
你得到组的“+4”是最后两个表达式 (([+])([0-9]+) ).
?: 指示 python 不要在输出中获取该组的 de 字符串。
你可以走测试路线。
使用 re.match
查看其是否有效
然后用 re.findall
得到结果
Python代码
import re
input = "1+2+3+4";
if re.match(r"^\d+\+\d+(?:\+\d+)*$", input) :
print ("Matched")
print (re.findall(r"\+|\d+", input))
else :
print ("Not valid")
输出
Matched
['1', '+', '2', '+', '3', '+', '4']
我想要一个正则表达式来匹配复杂的数学表达式。 但是我会要求一个更简单的正则表达式,因为这将是最简单的情况。
示例 输入: 1+2+3+4
我想分开每个字符:
[('1', '+', '2', '+', '3', '+', '4')]
有一个限制:必须至少有一个操作(即1+2
)。
我的正则表达式:([0-9]+)([+])([0-9]+)(([+])([0-9]+))*
或 (\d+)(\+)(\d+)((\+)(\d+))*
输出 re.findall('(\d+)(\+)(\d+)((\+)(\d+))*',"1+2+3+4")
:
[('1', '+', '2', '+4', '+', '4')]
为什么这不起作用? Python 是问题吗?
您需要 ([0-9]+)([+])([0-9]+)(?:([+])([0- 9]+))*
你得到组的“+4”是最后两个表达式 (([+])([0-9]+) ).
?: 指示 python 不要在输出中获取该组的 de 字符串。
你可以走测试路线。
使用 re.match
查看其是否有效
然后用 re.findall
Python代码
import re
input = "1+2+3+4";
if re.match(r"^\d+\+\d+(?:\+\d+)*$", input) :
print ("Matched")
print (re.findall(r"\+|\d+", input))
else :
print ("Not valid")
输出
Matched
['1', '+', '2', '+', '3', '+', '4']