【问题标题】:Regex numbers and letters in pythonpython中的正则表达式数字和字母
【发布时间】:2021-03-22 21:42:58
【问题描述】:

我正在弄清楚如何获得“02”和“05”或任何其他数字。当数字后面有字母(例如:'a' 和 'b' 或任何其他字母)时,我会遇到困难

title = "Nursing informatics S02E05ab Jack"       ->02 and 05
title = "Medical diagnosis   S06E06ku Peter"      ->06 and 06
title = "medical protection  S01E02bc Katharina"  ->01 and 02

我试过这样,但它总是返回“无”

result = re.search(r"\b(?:e?)?\s*(\d{2,3})(?:[a-z]?)?\b", title, re.IGNORECASE)

它应该只得到下一个数字S 和E。例如,books 2004 必须返回 None。

Thank you all

【问题讨论】:

  • 试试re.findall(r'\d+', title)
  • 它应该只得到数字'S'和'E'例如'books 2004'必须返回'None'
  • 然后使用try re.findall(r'[SE](\d+)', title)

标签: python python-3.x regex


【解决方案1】:

以下正则表达式函数(findall)可以识别所有指定的模式:

import re
s = "Nursing informatics S02E05ab Jack"
re.findall('[0-9]+', s)

输出:

['02', '05']

【讨论】:

    【解决方案2】:

    你可以使用

    \bS(?P<Season>\d+)E(?P<Episode>\d+)
    

    请参阅regex demo。 详情:

    • \b - 单词边界
    • S - 一封信 S
    • (?P&lt;Season&gt;\d+) - 组“季节”:一位或多位数字
    • E - E 信
    • (?P&lt;Episode&gt;\d+) - 组“剧集”:一位或多位数字

    见Python demo:

    import re
    title = "Nursing informatics S02E05ab Jack" 
    m = re.search(r'\bS(?P<Season>\d+)E(?P<Episode>\d+)', title)
    if m:
      print( m.groupdict() )
    # => {'Season': '02', 'Episode': '05'}
    

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 2015-10-24
      相关资源
      最近更新 更多