Search for a string in a line using regex
Question: I am searching for a string in the format XXXXX_XXXXX or XXXXXX_XXXXX or
XXXXXX in a line, where X is alphanumeric.

So the string before "_" is 5 or 6 characters long and the string after "_" is
always five or may be just 6 characters long without any underscore. I am
coding in Python.

Any help will be much appreciated.


Answer: Howabout this?

    
    
    ([a-zA-Z0-9]{5,6}_[a-zA-Z0-9]{5})|[a-zA-Z0-9]{6}
    

Full code example:

    
    
    import re
    pat = re.compile(r'^(([a-zA-Z0-9]{5,6}_[a-zA-Z0-9]{5})|[a-zA-Z0-9]{6})$')
    print pat.match('xxxxx_xxxxx') is not None    # True, 5 chars, underscore, 5 chars
    print pat.match('xxxxxx_xxxxx') is not None    # True, 6 chars, underscore, 5 chars
    print pat.match('xxxxxx') is not None    # True, 6 chars
    

**NOTE:** I previously wrote this, not realizing python doesn't support POSIX
character classes

    
    
    ([[:alnum:]]{5,6}_[[:alnum:]]{5})|[[:alnum:]]{6}
    

