1. 程式人生 > >Python match 將括號內外的資料分別取出來

Python match 將括號內外的資料分別取出來

i = R003(201000)

描述:將i分成兩部分“R003”和“201000”

import re
i = R003(201000)
num = re.match(r'(.*?)\((.*?)\)(.*?)',i).group(2)
name = re.match(r'(.*?)\((.*?)\)(.*?)',i).group(1)
print(num,name)

(.*?)\((.*?)\)(.*?)

其中(.*?)為最小匹配 \(\)分別表示以(和)作為分隔來取字串

re.match(r'(.*?)\((.*?)\)(.*?)',i)意思是分成兩部分,括號外group(1)=R003和括號內group(2)=201000

match.group()返回匹配物件的一個或多個分組。

match.group(0)(或match.group())表示匹配的所有欄位