社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python中的正则表达式lookahead[重复]

John Doyle Wagner • 7 年前 • 1851 次点击  

源字符串是:

# 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/43915
文章 [ 2 ]  |  最新文章 7 年前
Wiktor Stribiżew
Reply   •   1 楼
Wiktor Stribiżew    8 年前

这里有两件事要注意:

  • re.findall 如果regex模式中包含捕获组,则返回捕获的文本
  • 这个 r'\\.' 模式中的部分匹配两个连续字符, \ 以及换行符以外的任何字符。

见 findall reference :

如果模式中存在一个或多个组,则返回一个组列表;如果模式有多个组,则返回一个元组列表。空匹配将包含在结果中,除非它们触及另一个匹配的开头。

注意 使 芬德尔 只返回匹配值 ,您通常可以

  • 删除冗余捕获组(例如 (a(b)c) -gt; abc )
  • 将所有捕获组转换为 non-capturing (即,替换 ( 具有 (?: ) 除非 有引用模式中的组值的反向引用(请参见下文)
  • 使用 re.finditer 而不是( [x.group() for x in re.finditer(pattern, s)] )

对你来说, 芬德尔 返回所有捕获的空文本,因为 \\ 在内部 r'' 试图匹配文本的字符串文本 \ .

要匹配这些数字,您需要使用

-?\d*\.?\d+

regex匹配:

  • -? -可选减号
  • \d* -可选数字
  • \.? -可选小数分隔符
  • \d+ -一个或多个数字。

见 demo

这里是 IDEONE demo :

import re
s = r'abc123d, hello 3.1415926, this is my book'
pattern = r'-?\d*\.?\d+'
L = re.findall(pattern, s)
print(L)
vks
Reply   •   2 楼
vks    11 年前
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]