簡體   English   中英

使用正則表達式和 python 中的字符串中的數據提取復雜的 substring

[英]Extracting a complex substring using regex with data from a string in python

我有一個字符串說

text = 'i have on 31-Dec-08 USD 5234765 which I gave it in the donation"

我試過了:

pattern = r"^[\d]{2}.*,[\d]{3}$"
data = re.findall(pattern, text)

for s in data:
    print(s)

我想要的 output:

[2008 年 12 月 31 日,美元,5234765]

你可以那樣做

import re

regex = r"(\w+-\w+-\w+)|([A-Z]{3})|(\d+)"

test_str = "i have on 31-Dec-08 USD 5234765 which I gave it in the donation"


matches = re.findall(regex, test_str)
temp = [_ for tupl in matches for _ in tupl if _]

print(temp) #['31-Dec-08', 'USD', '5234765']
  • \w匹配任何單詞字符(相當於[a-zA-Z0-9_]
  • +匹配前一個令牌一次到無限次,盡可能多次,根據需要回饋(貪婪)
  • -匹配字符 - 字面意思(區分大小寫)
  • [AZ]{3}匹配大寫字母 3 次。
  • \d匹配一個數字(相當於[0-9]

暫無
暫無

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

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