当出现方括号时 re search



我试图通过解析已知格式的字符串来获得速度和方向的变量(基本上重新创建sscanf功能),如下所示的示例字符串

s = 'speed: 100.0, direction[ 12 ]'

然而,方向后面的方括号给我带来了问题。我试过了

checker=re.search('speed: (?P<speed>[-+]?(d+(.d*)?|.d+)([eE][-+]?d+)?), direction[ (?P<direc>d) ]',s)
print(f"[{checker['speed']},{checker['direc']}]")

在方括号前加上,如下所示:https://stackoverflow.com/a/74477176/4879524

然而,这是不工作,我不确定如何进行。如果我从字符串中删除方括号,它可以正常工作,但我希望尽可能避免这样做。

我的正则表达式知识是大约4小时以前,所以它可能是一个非常简单的修复。我不能使用解析模块作为替代,遗憾的是

带方括号-没有匹配,所以…

TypeError: 'NoneType' object is not subscriptable

不带方括号

s = 'speed: 100.0, direction 12'
checker = re.search('speed: (?P<speed>[-+]?(d+(.d*)?|.d+)([eE][-+]?d+)?), direction (?P<direc>d)',s)
print(f"[{checker['speed']},{checker['direc']}]")
>>[100.0,1] # (yes I forgot the + when I wrote it out in stack so here's the answer without the +, you can see that's not causing my error)

这个错误实际上与方括号无关。

你需要替换这个:

(?P<direc>d)

与这个:

(?P<direc>d+)
也就是说,整行代码变成了:
checker=re.search('speed: (?P<speed>[-+]?(d+(.d*)?|.d+)([eE][-+]?d+)?), direction[ (?P<direc>d+) ]',s)
更具体地说,你的正则表达式只匹配一个数字在方括号之间(例如"[ 1 ]"),而不是在方括号之间的一个或多个数字(例如您上面给出的"[ 12 ]"的实际示例)

您可以使用direction[?s*(?P<direc>d+)s*]?:

checker=re.search('speed: (?P<speed>[-+]?(d+(.d*)?|.d+)([eE][-+]?d+)?), direction[?s*(?P<direc>d+)s*]?',s)
print(f"[{checker['speed']},{checker['direc']}]")

输出:

# s = 'speed: 100.0, direction[ 12 ]'
[100.0,12]
# s = 'speed: 100.0, direction 12'
[100.0,12]

这是一个在字符串

中查找(十进制)数字的解决方案
import re
s = 'speed: 100.0, direction[ 12 ]'
# find (decimal) numbers in string. Only works if order is fixed
speed, direction = re.findall(r'd+.*d*', s)
# output: 100.0, 12
speed = float(speed)  # cast to number
direction = float(direction)  # cast to number

最新更新