簡體   English   中英

正則表達式:幫助查找字符串中的多個值 (Python)

[英]Regex: Help to find multiple values in string (Python)

我需要從 1 個字符串中提取 3 個不同的細節。

模式是:

  1. “C”后跟 3 位數字。
  2. 任何類型的字符和數字。 但是,一個/兩個字符后跟一個數字的順序總是如此。
  3. “S”后跟數字,可以包含特殊字符,如“-”和“_”。
  4. 不過最后一個“_”隔開一個迭代器,可以舍棄
  5. 有時沒有第二或第三個元素。

例子:

Input                   |      Expected output
---------------------------------------------------
C001F1S15_08            =>     ['C001','F1','S15']
C312PH2S1-06_5-0_12     =>     ['C312','PH2','S1-06_5-0']
C023_05                 =>     ['C023']
C002M5_02               =>     ['C002','M5']

如何才能做到這一點?

一切順利

嘗試這個:

(C\d{3})([A-RT-Z\d]+)?(S[\d\-_]+)?(?:_\d+)

結果: https://regex101.com/r/FETn0U/1

import re lines = ["C001F1S15_08", "C312PH2S1-06_5-0_12", "C023_05", "C002M5_02"] for line in lines: parts = line.split("_") if len(parts) > 1: parts = parts[:-1] line = "_".join(parts) print(line) print(re.findall("C\d{3}|S[A-Za-z0-9_@./#&+-]+|[A-Za-z]+\d+",line))

您可以像這樣提取值(使用 Avinash 的正則表達式)

import re

regex = re.compile(r"(C\d{3})([A-RT-Z\d]+)?(S[\d\-_]+)?(?:_\d+)")
text = "C001F1S15_08"
match = regex.match(text)
print(match.group(1))   # C001
print(match.group(2))   # F1
print(match.group(3))   # S15
print(match.groups())   # ('C001', 'F1', 'S15')
print(list(match.groups()[:3])) # ['C001', 'F1', 'S15']

有關更多信息,請參見此處 請記住.group(0)指的是整個匹配項,在本例中是輸入字符串。

下面的模式將做你想做的。我們丟棄最后一組。

^(C\d{3})([A-Z]+\d)?([-a-zA-Z\d]+_[\d-]+)?(_\w+)?

參見https://regex101.com/r/CKasXZ/2

result = []
str = ''.join(str.split('_')[:-1]) # For removing values after the last '_'.
result.append(str[0:4]) # for retrieve the 1st part of 4 elements.
for i in re.findall('[\w]{1,2}[0-9-]+', str[4:]): # The regex cut the end after each group of 1 or 2 letters + numbers and '-'. 
    result.append(i) # for retrive each values from the regex otherwise you have a list in a list.
result

我想你可以簡化循環,但我不知道如何。

暫無
暫無

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

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