Py学习  »  Python

Python RegExp capture Integer在某些模式之间的行为与普通模式不一样?[副本]

stackoverYC • 5 年前 • 1397 次点击  

源字符串是:

# Python 3.4.3
s = r'abc123d, hello 3.1415926, this is my book'

这是我的模式:

pattern = r'-?[0-9]+(\\.[0-9]*)?|-?\\.[0-9]+'

然而, re.search 可以给我正确的结果:

m = re.search(pattern, s)
print(m)  # output: <_sre.SRE_Match object; span=(3, 6), match='123'>

re.findall 把一张空名单扔掉:

L = re.findall(pattern, s)
print(L)  # output: ['', '', '']

为什么不能 芬德尔先生 给我期望的名单:

['123', '3.1415926']
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50441
 
1397 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Charif DZ
Reply   •   1 楼
Charif DZ    5 年前
s = r'abc123d, hello 3.1415926, this is my book'
print re.findall(r'-?[0-9]+(?:\.[0-9]*)?|-?\.[0-9]+',s)

你不需要 escape 使用时两次 raw mode .

输出: ['123', '3.1415926']

返回类型还将是 strings 。如果希望返回类型为 integers floats 使用 map

import re,ast
s = r'abc123d, hello 3.1415926, this is my book'
print map(ast.literal_eval,re.findall(r'-?[0-9]+(?:\.[0-9]*)?|-?\.[0-9]+',s))

输出: [123, 3.1415926]