[英]What does re.match('(…),..', string) return?
我是python的新手,有一個困惑:
type = order_change_separate_t
re.match('(...)..', type).group(1)
返回什么? 它會返回order_change_separate嗎?
提前致謝!
您應該使用python的交互式外殼來嘗試以下操作:
sgupta-3:~ sgupta$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> type = "order_change_separate_t"
>>> import re
>>> print re.match('(...)..', type).group(1)
ord
它打印“ ord”
(...)是捕獲組定義的組1,這3個點匹配ord。
print re.match('(.*)..', type).group(1)
將返回“ order_change_separate”
上面的代碼顯然是一種非常粗糙且不可擴展的提取方法,因為它僅適用於“ order_change_separate”,后面緊跟兩個字符。
更好的方法是使用量化器作為上述用戶“ aelor”。
它會返回ord
。
因為您在capture group
()
只有三個字符
如果您想order_change_separate
使用此:
re.match('(.*?)_.$', type).group(1)
這將匹配最后一個underscore followed by a character
之前的所有underscore followed by a character
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.