[英]Regex: Help to find multiple values in string (Python)
我需要從 1 個字符串中提取 3 個不同的細節。
模式是:
例子:
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']
如何才能做到這一點?
一切順利
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+)?
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.