Py学习  »  Python

python正则表达式-提取浮点模式

Enrique Bruzual • 7 年前 • 2357 次点击  

我试图从字符串中提取一个特定的“float”,它包含多个格式化的“integer”、“float”和日期。所讨论的特定“浮动”由一些标准化文本主持。

字符串示例

my_string = """03/14/2019 07:07 AM
💵Soles in mDm : 2864.35⬇
🔶BTC purchase in mdm: 11,202,782.0⬇
"""

我已经能够提取出所需的浮动模式, 2864.35 ,从 my_string 但是,如果这个特定的float在模式中发生了变化,或者出现了另一个具有相同格式的float,我的脚本将不会返回所需的结果

regex = r"(\d+\.\d+)"
matches = re.findall(regex, my_string)
for match in matches:
    print(match)
  • 由于数值格式不一致,它可能会截断所需的浮点
  • 它可能会打印两个浮点数,因为不需要的浮点数的数字模式太相似,无法由当前正则表达式过滤掉。 regex

正则表达式的期望返回 正则表达式

  • 带有灵活整数部分的浮点数,有时省略逗号,即45000.50,其他为45000.50
  • 唯一行标识符: Soles 可能是大写/小写
  • 行标识符:浮点前缀 :
  • 它应该只会回来 一个浮子

仅在字符串的第二行中所需浮点的一些方差

下面是同一行的三个例子,第二行 我的绳子 . regex应该只能返回第二行,尽管有任何变化,比如 鞋底 或 鞋底

  • MDM鞋底:2864.35
  • 鞋底MDM:2864.35
  • MDM鞋底:2864.355

在编辑或重新编写当前正则表达式时提供的任何帮助 正则表达式 非常感谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40002
文章 [ 2 ]  |  最新文章 7 年前
Always Sunny
Reply   •   1 楼
Always Sunny    7 年前

如果要匹配多个实例,只需添加 g 另一方面,它只匹配单个实例。 REGEX

(?<=:)\s?([\d,]*\.\d+)

对于python,

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?<=:)\s?([\d,]*\.\d+)"

test_str = ("\n"
    "    💵Soles in mDm : 2864.35⬇\n"
    "    soles MDM: 2,864.35\n"
    "    Soles in mdm :2,864.355\n")

matches = re.search(regex, test_str, re.IGNORECASE)

if matches:
    print ("Match was found at {start}-{end}: {match}".format(start = matches.start(), end = matches.end(), match = matches.group()))

    for groupNum in range(0, len(matches.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = matches.start(groupNum), end = matches.end(groupNum), group = matches.group(groupNum)))
FailSafe
Reply   •   2 楼
FailSafe    7 年前

编辑-hmmm…如果它必须跟随 soles 希望这能帮上忙

试试这些,我的控制台不能接受额外的字符,但基于您的输入:

>>> my_string = """03/14/2019 07:07 AM
Soles in mDm : 2864.35
BTC purchase in mdm: 11,202,782.0
Soles in mDm : 2864.35
soles MDM: 2,864.35
Soles in mdm :2,864.355
"""


>>> re.findall('(?i)soles[\S\s]*?([\d]+[\d,]*\.[\d]+)', my_string)

#Output
['2864.35', '2864.35', '2,864.35', '2,864.355']



>>> re.findall('[S|s]oles[\S\s]*?([\d]+[\d,]*\.[\d]+)', my_string)

#Output
['2864.35', '2864.35', '2,864.35', '2,864.355']