0

The problem is how to implement conditions with regex. We have got this:

regex = '"Tom":{"c":(.+?),"b":(.+?),"a":(.+?)}|"Tom":{"a":(.+?),"c":(.+?),"b":(.+?)}'

We want to do different things to the regex based on which regex expression will be found. How do we encounter this? How do we access this with if statements?

Say: if regex[0]: print 'Hi' else: print 'Hello' Basically, I just don't know how to ask python which regex has been found and used.

I mean what'd the syntax be?

nutship
  • 4,624
  • 13
  • 47
  • 64

1 Answers1

2

You should be able to do what you want using named regular expressions http://docs.python.org/2/library/re.html

regex = '(?P<first>"Tom":{"c":(.+?),"b":(.+?),"a":(.+?)})|(?P<second>"Tom":{"a":(.+?),"c":(.+?),"b":(.+?)})'
# Careful as this raises an exception if no match was found
m = re.search( regex, somestring ).groupdict()
if m['first']:
    print 'First'
else:
    print 'Second'
Necrolyte2
  • 738
  • 5
  • 13
  • The P just signifies that you are making a named regular expression. If I had to guess why they chose P, it would probably be for Pattern – Necrolyte2 Mar 09 '13 at 14:35
  • @nutship No, for the P, see (http://docs.python.org/2/howto/regex.html#non-capturing-and-named-groups) : _"Python adds an extension syntax to Perl’s extension syntax. If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python."_ – eyquem Mar 09 '13 at 14:45
  • because I had to know...http://stackoverflow.com/questions/10059673/named-regular-expression-group-pgroup-nameregexp-what-does-p-stand-for – CrayonViolent Mar 09 '13 at 14:45