Or statements for complex regex formation in python
Question: I need to formulate a regex to pick up only the first part of a particular
string rather than the second part. For example:

    
    
          (part1)                        (Part2)    
            SAI                           Table
    
    
                                          Cloth
    
    
           DARA                                 
    

I want to extract only `SAI` (i.e. part1 and not part2). Notice that the 2nd
line is empty in part 1 and hence it should return an empty space (and not
`cloth`). The same regex must work for all three cases of strings. In the case
of string2 part one must return a blank space and not `table`. There is no
certain length of spaces between the two parts. It varies.

This is the regex I tried, but it only works for string1 and string3:

    
    
    [\s]{1,}((?:[a-zA-Z)(@\-,."'',&*]+[\s]?)+)[\s]{2,}
    

Is there any way to write a regex that would work in this case?

I can only use regex here as I need it to return any string present there. The
string can be alpha-numerals and may contain the most popularly used symbols
present in my earlier regex. The space between the two is never fixed.

I also need it to return a space where it is empty in part 1. We can ignore
part 2. But I have to make sure that the regex does not match part 2.


Answer: If the first column (_part1_) is **always** followed by 2 spaces, whereas the
second (_part2_) is not, you can rely on that condition to prevent a match in
the last column. We can use the [lookahead](http://www.regular-
expressions.info/lookaround.html) `(?=[\t ]{2})` to assert for 2 consecutive
spaces or tabs.

**Code**

    
    
    import re
    
    patt = r'^[\t ]*(\S+(?:[\t ]\S+)*(?=[\t ]{2})| )'
    str = r'''
          (part1)                        (Part2)    
            SAI                           Table
                                          Cloth
           DARA                                 
    '''
    
    print re.findall(patt, str, re.MULTILINE)
    

**Output**

    
    
    ['(part1)', 'SAI', ' ', 'DARA']
    

`[ideone demo](http://ideone.com/lqvLXX)`

You may as well change `\S` to `[a-zA-Z)(@\-,."'',&*]` to limit the allowed
characters.

