2011年11月10日 星期四

Python re module:re.match(),re.search,matchObj.group(),matchObj.groups()

In a nutshell, 
match() only attempts to match a pattern at the beginning of a string where 
search() will match a pattern anywhere in a string. For example:
>>>
>>> re.match("o", "dog")  # No match as "o" is not the first letter of "dog".
>>> re.search("o", "dog") # Match as search() looks everywhere in the string.
<_sre.SRE_Match object at ...>

match() has an optional second parameter that gives an index in the string where the search is to start:
>>> pattern = re.compile("o")
>>> pattern.match("dog")      # No match as "o" is not at the start of "dog."

# Equivalent to the above expression as 0 is the default starting index:
>>> pattern.match("dog", 0)

# Match as "o" is the 2nd character of "dog" (index 0 is the first):
>>> pattern.match("dog", 1)
<_sre.SRE_Match object at ...>
>>> pattern.match("dog", 2)   # No match as "o" is not the 3rd character of "dog."
#如何使用matchObj.group(),matchObj.groups()
>>> 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')

沒有留言:

張貼留言