簡體   English   中英

python 中的正則表達式數字和字母

[英]Regex numbers and letters in python

我正在弄清楚如何獲得“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)

它應該只得到下一個SE的數字。 例如, books 2004必須返回None

Thank you all

以下正則表達式 function (findall) 可以識別所有指定的模式:

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

Output:

['02', '05']

您可以使用

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

請參閱正則表達式演示 詳情

  • \b - 單詞邊界
  • S - 字母S
  • (?P<Season>\d+) - 組“季節”:一位或多位數字
  • E - E字母
  • (?P<Episode>\d+) - 組“Episode”:一位或多位數字

請參閱Python 演示

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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM