python - difference b/w [ab] and (a|b) in regex match? -



python - difference b/w [ab] and (a|b) in regex match? -

i knew [] denotes set of allowable characters -

>>> p = r'^[ab]$' >>> >>> re.search(p, '') >>> re.search(p, 'a') <_sre.sre_match object @ 0x1004823d8> >>> re.search(p, 'b') <_sre.sre_match object @ 0x100482370> >>> re.search(p, 'ab') >>> re.search(p, 'ba')

but ... today came across look vertical bars within parenthesis define mutually exclusive patterns -

>>> q = r'^(a|b)$' >>> >>> re.search(q, '') >>> re.search(q, 'a') <_sre.sre_match object @ 0x100498dc8> >>> re.search(q, 'b') <_sre.sre_match object @ 0x100498e40> >>> re.search(q, 'ab') >>> re.search(q, 'ba')

this seems mimic same functionality above, or missing something?

ps: in python parenthesis used define logical groups of matched text. if utilize sec technique, how utilize parenthesis both jobs?

in case same.

however, alternation not limited single character. instance,

^(hello|world)$

will match "hello" or "world" (and only these 2 inputs) while

^[helloworld]$

would match single character ("h" or "w" or "d" or whatnot).

happy coding.

python regex

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -