Backward matching with regular expressions

Posted on

# -*- coding: utf-8 -*-

s = """I wan't to do 'backward matching': In my case match a series of  numbers backwards, e.g., with "1 2 3 4" I want to pick out  "2 3 4" rather than "1 2 3" with a regular expression such as  "d+s+d+s+d+". Within Python and using re.findall() the  na??ve application gets you "1 2 3". One way would be to reverse  the string - in Python with s[::-1] - and write the regular  expression 'backwards'. However, a solution that seems less  complex simply extends the regular expression repeating the  subpattern with a 'match 0 or more time' preamble. In my case  that would read '(?:d+s+)*(d+s+d+s+d+)'. The code below  behaves properly with the string that this sentence is part of.  """  import re pattern1 = "d+s+d+s+d+" print(re.findall(pattern1, s))  pattern2 = "(?:d+s+)*(d+s+d+s+d+)" print(re.findall(pattern2, s))  #

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s