gpt4 book ai didi

python - 运动正则表达式 G 代码 +Python

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:08 25 4
gpt4 key购买 nike

我有以下正则表达式:

self.PosCheck = re.compile('[gG0-3]{1,3}|\s{1,2}[xX]-?([0-9.]{1,15})|\s[yY]-?([0-9.]{1,15})|\s[zZ]-?([0-9.]{1,15})')

它工作得非常好,可以检测每个轴的每个值,并将这些值分类到不同的组中(如果可用)。例如:position_response = "G0 X100 Y200 Z300"

regline = self.PosCheck.findall(position_response)
for i in regline:
if i[0]:
print (i[0]) #prints 100
if i[1]:
print (i[1]) #prints 200
if i[2]:
print (i[2]) #prints 300

但是否有 gG0-3 是独立的。如果没有 gG0-3,则正则表达式不应分组提供任何答案。我该如何解决这个问题?

最佳答案

我会选择命名组和单个匹配

import re

PosCheck = re.compile(
'(?i)^[gG0-3]{1,3}(?:\s+x-?(?P<x>[0-9.]{1,15})|\s+y-?(?P<y>[0-9.]{1,15})|\s+z-?(?P<z>[0-9.]{1,15}))*$')

for position_response in [
"G0 X100 Y200 Z300",
"G0 x100 z20",
"x150 y30",
]:
i = PosCheck.match(position_response)
if i:
print(position_response, '->', i.groupdict())
else:
print(position_response, '->', None)

输出:

G0 X100 Y200 Z300 -> {'x': '100', 'y': '200', 'z': '300'}
G0 x100 z20 -> {'x': '100', 'y': None, 'z': '20'}
x150 y30 -> None

关于python - 运动正则表达式 G 代码 +Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41074050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com