【问题标题】:Ignoring data under a specific section in a string using Python使用Python忽略字符串中特定部分下的数据
【发布时间】:2019-05-06 19:48:43
【问题描述】:

我有一个如下所示的字符串

line="record of Students Name Codes:  AC1.123  XYZ12.67  the student is math major first hisory: XY12.34 good performer second history M12.78 N23.76 faculty Miss Cooper"

我想从该行中提取一些代码。我正在使用下面的程序。我想忽略历史部分中的代码。

我可以知道如何忽略其中有历史记录的部分中的代码

import re
regular_expression = re.compile(r'\b[A-Z]+\d{1,2}\.*\d{1,2}\w{0,2}\b', re.I)
matches = regular_expression.findall(line)
for match in matches:
    print (match)

预期输出

AC1.123
XYZ12.67

当前输出:

AC1.123
XYZ12.67
XY12.34
M12.78
N23.76

【问题讨论】:

  • 这里如何定义块?为什么不先分块呢?
  • 是的,我在想如何在这里定义块?

标签: regex python-3.x string


【解决方案1】:

您可以匹配历史记录中您不想要的所有值,然后在一个组中捕获您想要的内容:

\bhistory:? [A-Z]+\d+\.\d+(?: [A-Z]+\d+\.\d+)*|([A-Z]+\d+\.\d+(?: [A-Z]+\d+)*)

说明

  • \bhistory:? 字边界、匹配历史记录、可选冒号和空格
  • [A-Z]+\d+\.\d+ 匹配 1+ 次 a-z、1+ 位、点字面量和 1+ 位
  • (?:非捕获组
    • [A-Z]+\d+\.\d+ 重复匹配先前的模式,并在前面添加一个空格
  • )*关闭非捕获组并重复0+次
  • |
  • (抓包组
    • [A-Z]+\d+\.\d+ 与第一个模式匹配
    • (?: [A-Z]+\d+)* 重复相同的模式,前面加一个空格
  • )

Regex demo | Python demo

我认为hisory 是一个错字,应该是history

例如:

import re
line = "record of Students Name Codes:  AC1.123  XYZ12.67  the student is math major first history: XY12.34 good performer second history M12.78 N23.76 faculty Miss Cooper"
regular_expression = re.compile(r'\bhistory:? [A-Z]+[0-9]+\.[0-9]+(?: [A-Z]+[0-9]+\.[0-9]+)*|([A-Z]+[0-9]+\.[0-9]+(?: [A-Z]+[0-9]+)*)', re.I)
matches = regular_expression.findall(line)
print(list(filter(None, matches)))

结果

['AC1.123', 'XYZ12.67']

【讨论】:

    【解决方案2】:

    我不太确定您想要的规则是什么,但这可能有助于您设计an expression

    (AC|XYZ)([0-9]+.[0-9]+)
    

    图表

    这张图显示了这样的表达式是如何工作的:

    示例测试

    # -*- coding: UTF-8 -*-
    import re
    
    string = "record of Students Name Codes:  AC1.123  XYZ12.67  the student is math major first hisory: XY12.34 good performer second history M12.78 N23.76 faculty Miss Cooper"
    expression = r'((AC|XYZ)([0-9]+.[0-9]+))'
    match = re.search(expression, string)
    if match:
        print("YAAAY! \"" + match.group(1) + "\" is a match ? ")
    else: 
        print('? Sorry! No matches! Something is not right! Call 911 ?')
    

    【讨论】:

    • 代码对 AC 或 XYZ 不严格。可以是任何东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 2018-09-27
    • 2022-07-27
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多