Search code examples
pythonregexmetacharacters

Python Regular Expression and Metacharacters


There is a variable which is:

line="s(a)='asd'"

I am trying to find a part which includes "s()".

I tried using:

re.match("s(*)",line)

But it seems that It is not able to search for characters that includes ( )

Is there a way to find it and print it in python?


Solution

  • Your regex is the problem here.

    You can use:

    >>> line="s(a)='asd'"
    >>> print re.findall(r's\([^)]*\)', line)
    ['s(a)']
    

    RegEx Breakup:

    s     # match letter s
    \(    # match literal (
    [^)]* # Using a negated character class, match 0 more of any char that is not )
    \)    $ match literal (
    
    • r is used for raw string in Python.