Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:获取正则表达式成功匹配的组数_Python_Regex - Fatal编程技术网

Python:获取正则表达式成功匹配的组数

Python:获取正则表达式成功匹配的组数,python,regex,Python,Regex,我想用python从字符串中捕获数据和数字。该字符串是来自RF传感器的测量值,因此可能因传输不良而损坏。来自传感器的字符串看起来像此PA1015.7 TMPA20.53 HUM76.83 我的答复是: s= re.search('^(\D+)([0-9.]+'),message) 现在,在继续之前,我想检查我是否确实正确地收到了两个匹配项,或者字符串是否有误 所以我试着: len(s) 但这是错误的: Traceback (most recent call last): File "&l

我想用python从字符串中捕获数据和数字。该字符串是来自RF传感器的测量值,因此可能因传输不良而损坏。来自传感器的字符串看起来像此PA1015.7 TMPA20.53 HUM76.83

我的答复是:

s= re.search('^(\D+)([0-9.]+'),message)
现在,在继续之前,我想检查我是否确实正确地收到了两个匹配项,或者字符串是否有误

所以我试着:

len(s)
但这是错误的:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type '_sre.SRE_Match' has no len()

缺少什么?

您应该使用
findall
而不是使用
search

s = re.findall('(\D+)([0-9.]+)',message)
print("matched " + str(len(s)))

search
仅以布尔值的形式返回输入字符串中是否存在匹配项。

我确实需要访问匹配组元素以便稍后处理。(我认为这会消除findall)–为什么会消除findall?当findall返回匹配元素列表时,您将能够访问匹配的组。最好删除前导插入符号
^
,以匹配
消息中的多个子字符串。是@tshiono,事实上,这是我回答中的一个关键错误,感谢您指出!
s = re.findall('(\D+)([0-9.]+)',message)
print("matched " + str(len(s)))