python中的match物件

2021-08-17 04:19:58 字數 1969 閱讀 3245

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

不含引數的時候,返回整個匹配物件

含有乙個引數的時候,返回引數對應分組的物件

含有多個引數的時候,以元組的形式返回引數對應的分組

>>> m = re.match(r"(\w+) (\w+)", "isaac newton, physicist")

>>> m.group(0) # the entire match

'isaac newton'

>>> m.group(1) # the first parenthesized subgroup.

'isaac'

>>> m.group(2) # the second parenthesized subgroup.

'newton'

>>> m.group(1, 2) # multiple arguments give us a tuple.

('isaac', 'newton')

如果正規表示式中使用了(?..)命名分組,那麼group引數也可以傳遞相應的name來返回匹配的group。

>>> m = re.match(r"(?p\w+) (?p\w+)", "malcolm reynolds")

>>> m.group('first_name')

'malcolm'

>>> m.group('last_name')

'reynolds'

當然,此時也是可以使用陣列表示相應的分組的。

>>> m.group(1)

'malcolm'

>>> m.group(2)

'reynolds'

match物件還有其他函式,如span(),start(),end(),string,re,pos,endpos,lastindex,lastgroup

in [68]: m.start()

out[68]: 0

in [83]: m.start(1)

out[83]: 0

in [84]: m.start(2)

out[84]: 8

in [85]: m.end(1)

out[85]: 7

in [87]: m.end(2)

out[87]: 16

in [69]: m.end()

out[69]: 16

in [70]: m.span()

out[70]: (0, 16)

in [88]: m.span(1)

out[88]: (0, 7)

in [89]: m.span(2)

out[89]: (8, 16)

in [72]: m.string

out[72]: 'malcolm reynolds'

in [73]: m.re

out[73]: re.compile(r'(?p\w+) (?p\w+)', re.unicode)

in [74]: m.pos

out[74]: 0

in [75]: m.endpos

out[75]: 16

out[76]: 2

in [77]: m.lastgroup #最後捕獲分組的名稱,如果沒有分組**獲或者捕獲分組沒有名字,那麼結果為none

out[77]: 'last_name'

其中的lastindex還是有點不太懂

groups([default]): 

以元組形式返回全部分組截獲的字串。相當於呼叫group(1,2,…last)。default表示沒有截獲字串的組以這個值替代,預設為none。

groupdict([default]): 

返回以有別名的組的別名為鍵、以該組截獲的子串為值的字典,沒有別名的組不包含在內。default含義同上。

python中的match和search的區別

match string pos endpos re.match pattern,string flags search string pos endpos re.search pattern,string flags match 從指定的位置匹配到結尾,必須開頭一模一樣的對應,search 也是在...

re模組中match物件中的方法和屬性

match物件的方法和屬性 屬性和方法 描述pos 搜尋的開始位置 endpos 搜尋的結束位置 string 搜尋的字串 re當前使用的正規表示式物件 lastindex 最後匹配的組索引 lastgroup 最後匹配的組名 group index 某個組匹配的結果 groups 所有分組的匹配結...

re模組中match物件的方法和屬性

屬性和方法 說 明 pos搜尋的開始位置 endpos 搜尋的結束位置 string 搜尋的字串 re當前使用的正規表示式的物件 lastindex 最後匹配的組索引 lastgroup 最後匹配的組名 group index 0 某個分組的匹配結果。如果index等於0,便是匹配整個正規表示式 g...