Home > OS >  RE Compile giving error unbalanced parenthesis
RE Compile giving error unbalanced parenthesis

Time:06-09

import re
import os
re_filename = re.compile(
    r"^(?:.*"   os.sep   r")?"  
    r"([^@]*?)"  
    r"(?:@([^.]*?))?"  
    r"(?:\.yang|\.yin)*"  
    r"\.(yang|yin)$")

Traceback (most recent call last): File "", line 6, in File "C:\Python27\lib\re.py", line 190, in compile return _compile(pattern, flags) File "C:\Python27\lib\re.py", line 242, in _compile raise error, v sre_constants.error: unbalanced parenthesis

CodePudding user response:

When os.sep is a backslash, then it escapes the closing ")" that follows it, and so you don't have a closing parenthesis in the meaning of a capture group, but a literal ")".

So make sure the os.sep character is taken literally:

import re
import os
re_filename = re.compile(
    r"^(?:.*"   re.escape(os.sep)   r")?"  
    r"([^@]*?)"  
    r"(?:@([^.]*?))?"  
    r"(?:\.yang|\.yin)*"  
    r"\.(yang|yin)$")
  • Related