群組(grouping): 用小括號包起來
e.g.
import re
m = re.search('it is (fine (today))', 'it is fine today')
m.group(0)
m.group(1)
m.group(2)
#以上程式會依續印出完整字串、左起第一組小括號、第二組小括號
import re
f = open('/tmp/auth.log')
for i in f:
regex = re.search(r'200\.[0-9]{1,3}\.[0-9]{1,3}\.([0-9]{1,3})', i)
#加上小括號
if regex:
print regex.group(1)
#加上小括號所出現的 index (從 1 開始算)
f.close()
-----------------------------------------------------------------------------------------------
字串切割重組
e.g.
import re
text = "hello123world456"
t="\t".join(re.split(r"\d+", text))
print t
-----------------------------------------------------------------------------------------------
\w = [a-zA-Z0-9_]
\s = [\t\n \r\f\v]
\d = [0-9] \w = [a-zA-Z0-9_]
\s = [\t\n \r\f\v]
\d = [0-9]
大寫則有反義的用途,
例如 \D 是非數字,\W 代表非英數字、\S 代表非空白字元
------------------------------------------------------------------------------------------------
ref.
http://fannys23.pixnet.net/blog/post/15367167#comment-59040007
沒有留言:
張貼留言