Python sre_constants.error() Examples

The following are 30 code examples of sre_constants.error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sre_constants , or try the search function .
Example #1
Source File: clues.py    From WAD with GNU General Public License v3.0 6 votes vote down vote up
def compile_clues(self):
        # compiling regular expressions
        for app in self.apps:
            regexps = {}
            for key in list(self.apps[app]):
                if key in ['script', 'html', 'url']:
                    try:
                        regexps[key + "_re"] = list(six.moves.map(self.compile_clue, self.apps[app][key]))
                    except sre_constants.error:
                        del self.apps[app][key]
                if key in ['meta', 'headers', 'js', 'cookies']:
                    try:
                        regexps[key + "_re"] = dict((entry, self.compile_clue(self.apps[app][key][entry]))
                                                    for entry in self.apps[app][key])
                    except sre_constants.error:
                        del self.apps[app][key]
            self.apps[app].update(regexps) 
Example #2
Source File: test_re.py    From jawfish with MIT License 6 votes vote down vote up
def test_sre_character_class_literals(self):
        for i in [0, 8, 16, 32, 64, 127, 128, 255, 256, 0xFFFF, 0x10000, 0x10FFFF]:
            if i < 256:
                self.assertIsNotNone(re.match(r"[\%o]" % i, chr(i)))
                self.assertIsNotNone(re.match(r"[\%o8]" % i, chr(i)))
                self.assertIsNotNone(re.match(r"[\%03o]" % i, chr(i)))
                self.assertIsNotNone(re.match(r"[\%03o0]" % i, chr(i)))
                self.assertIsNotNone(re.match(r"[\%03o8]" % i, chr(i)))
                self.assertIsNotNone(re.match(r"[\x%02x]" % i, chr(i)))
                self.assertIsNotNone(re.match(r"[\x%02x0]" % i, chr(i)))
                self.assertIsNotNone(re.match(r"[\x%02xz]" % i, chr(i)))
            if i < 0x10000:
                self.assertIsNotNone(re.match(r"[\u%04x]" % i, chr(i)))
                self.assertIsNotNone(re.match(r"[\u%04x0]" % i, chr(i)))
                self.assertIsNotNone(re.match(r"[\u%04xz]" % i, chr(i)))
            self.assertIsNotNone(re.match(r"[\U%08x]" % i, chr(i)))
            self.assertIsNotNone(re.match(r"[\U%08x0]" % i, chr(i)+"0"))
            self.assertIsNotNone(re.match(r"[\U%08xz]" % i, chr(i)+"z"))
        self.assertIsNotNone(re.match(r"[\U0001d49c-\U0001d4b5]", "\U0001d49e"))
        self.assertRaises(re.error, re.match, r"[\911]", "")
        self.assertRaises(re.error, re.match, r"[\x1z]", "")
        self.assertRaises(re.error, re.match, r"[\u123z]", "")
        self.assertRaises(re.error, re.match, r"[\U0001234z]", "")
        self.assertRaises(re.error, re.match, r"[\U00110000]", "") 
Example #3
Source File: mpfexp.py    From mpfshell with MIT License 6 votes vote down vote up
def mget(self, dst_dir, pat, verbose=False):

        try:

            files = self.ls(add_dirs=False)
            find = re.compile(pat)

            for f in files:
                if find.match(f):
                    if verbose:
                        print(" * get %s" % f)

                    self.get(f, dst=posixpath.join(dst_dir, f))

        except sre_constants.error as e:
            raise RemoteIOError("Error in regular expression: %s" % e) 
Example #4
Source File: test_re.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_symbolic_groups(self):
        re.compile('(?P<a>x)(?P=a)(?(a)y)')
        re.compile('(?P<a1>x)(?P=a1)(?(a1)y)')
        self.assertRaises(re.error, re.compile, '(?P<a>)(?P<a>)')
        self.assertRaises(re.error, re.compile, '(?Px)')
        self.assertRaises(re.error, re.compile, '(?P=)')
        self.assertRaises(re.error, re.compile, '(?P=1)')
        self.assertRaises(re.error, re.compile, '(?P=a)')
        self.assertRaises(re.error, re.compile, '(?P=a1)')
        self.assertRaises(re.error, re.compile, '(?P=a.)')
        self.assertRaises(re.error, re.compile, '(?P<)')
        self.assertRaises(re.error, re.compile, '(?P<>)')
        self.assertRaises(re.error, re.compile, '(?P<1>)')
        self.assertRaises(re.error, re.compile, '(?P<a.>)')
        self.assertRaises(re.error, re.compile, '(?())')
        self.assertRaises(re.error, re.compile, '(?(a))')
        self.assertRaises(re.error, re.compile, '(?(1a))')
        self.assertRaises(re.error, re.compile, '(?(a.))') 
Example #5
Source File: test_re.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_other_escapes(self):
        self.assertRaises(re.error, re.compile, "\\")
        self.assertEqual(re.match(r"\(", '(').group(), '(')
        self.assertIsNone(re.match(r"\(", ')'))
        self.assertEqual(re.match(r"\\", '\\').group(), '\\')
        self.assertEqual(re.match(r"[\]]", ']').group(), ']')
        self.assertIsNone(re.match(r"[\]]", '['))
        self.assertEqual(re.match(r"[a\-c]", '-').group(), '-')
        self.assertIsNone(re.match(r"[a\-c]", 'b'))
        self.assertEqual(re.match(r"[\^a]+", 'a^').group(), 'a^')
        self.assertIsNone(re.match(r"[\^a]+", 'b'))
        re.purge()  # for warnings
        for c in 'ceghijklmopquyzCEFGHIJKLMNOPQRTUVXY':
            warn = FutureWarning if c in 'Uu' else DeprecationWarning
            with check_py3k_warnings(('', warn)):
                self.assertEqual(re.match('\\%c$' % c, c).group(), c)
                self.assertIsNone(re.match('\\%c' % c, 'a'))
        for c in 'ceghijklmopquyzABCEFGHIJKLMNOPQRTUVXYZ':
            warn = FutureWarning if c in 'Uu' else DeprecationWarning
            with check_py3k_warnings(('', warn)):
                self.assertEqual(re.match('[\\%c]$' % c, c).group(), c)
                self.assertIsNone(re.match('[\\%c]' % c, 'a')) 
Example #6
Source File: mpfexp.py    From mpfshell with MIT License 6 votes vote down vote up
def rm(self, target):

        try:
            # 1st try to delete it as a file
            self.eval("uos.remove('%s')" % (self._fqn(target)))
        except PyboardError:
            try:
                # 2nd see if it is empty dir
                self.eval("uos.rmdir('%s')" % (self._fqn(target)))
            except PyboardError as e:
                # 3rd report error if nor successful
                if _was_file_not_existing(e):
                    if self.sysname == "WiPy":
                        raise RemoteIOError(
                            "No such file or directory or directory not empty: %s"
                            % target
                        )
                    else:
                        raise RemoteIOError("No such file or directory: %s" % target)
                elif "EACCES" in str(e):
                    raise RemoteIOError("Directory not empty: %s" % target)
                else:
                    raise e 
Example #7
Source File: mpfexp.py    From mpfshell with MIT License 6 votes vote down vote up
def mput(self, src_dir, pat, verbose=False):

        try:

            find = re.compile(pat)
            files = os.listdir(src_dir)

            for f in files:
                if os.path.isfile(f) and find.match(f):
                    if verbose:
                        print(" * put %s" % f)

                    self.put(posixpath.join(src_dir, f), f)

        except sre_constants.error as e:
            raise RemoteIOError("Error in regular expression: %s" % e) 
Example #8
Source File: test_re.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_symbolic_groups(self):
        re.compile('(?P<a>x)(?P=a)(?(a)y)')
        re.compile('(?P<a1>x)(?P=a1)(?(a1)y)')
        self.assertRaises(re.error, re.compile, '(?P<a>)(?P<a>)')
        self.assertRaises(re.error, re.compile, '(?Px)')
        self.assertRaises(re.error, re.compile, '(?P=)')
        self.assertRaises(re.error, re.compile, '(?P=1)')
        self.assertRaises(re.error, re.compile, '(?P=a)')
        self.assertRaises(re.error, re.compile, '(?P=a1)')
        self.assertRaises(re.error, re.compile, '(?P=a.)')
        self.assertRaises(re.error, re.compile, '(?P<)')
        self.assertRaises(re.error, re.compile, '(?P<>)')
        self.assertRaises(re.error, re.compile, '(?P<1>)')
        self.assertRaises(re.error, re.compile, '(?P<a.>)')
        self.assertRaises(re.error, re.compile, '(?())')
        self.assertRaises(re.error, re.compile, '(?(a))')
        self.assertRaises(re.error, re.compile, '(?(1a))')
        self.assertRaises(re.error, re.compile, '(?(a.))') 
Example #9
Source File: test_re.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_symbolic_groups(self):
        re.compile('(?P<a>x)(?P=a)(?(a)y)')
        re.compile('(?P<a1>x)(?P=a1)(?(a1)y)')
        self.assertRaises(re.error, re.compile, '(?P<a>)(?P<a>)')
        self.assertRaises(re.error, re.compile, '(?Px)')
        self.assertRaises(re.error, re.compile, '(?P=)')
        self.assertRaises(re.error, re.compile, '(?P=1)')
        self.assertRaises(re.error, re.compile, '(?P=a)')
        self.assertRaises(re.error, re.compile, '(?P=a1)')
        self.assertRaises(re.error, re.compile, '(?P=a.)')
        self.assertRaises(re.error, re.compile, '(?P<)')
        self.assertRaises(re.error, re.compile, '(?P<>)')
        self.assertRaises(re.error, re.compile, '(?P<1>)')
        self.assertRaises(re.error, re.compile, '(?P<a.>)')
        self.assertRaises(re.error, re.compile, '(?())')
        self.assertRaises(re.error, re.compile, '(?(a))')
        self.assertRaises(re.error, re.compile, '(?(1a))')
        self.assertRaises(re.error, re.compile, '(?(a.))') 
Example #10
Source File: json_parser.py    From lark with MIT License 6 votes vote down vote up
def match_examples(self, parse_fn, examples):
        """ Given a parser instance and a dictionary mapping some label with
            some malformed syntax examples, it'll return the label for the
            example that bests matches the current error.
        """
        assert self.state is not None, "Not supported for this exception"

        candidate = None
        for label, example in examples.items():
            assert not isinstance(example, STRING_TYPE)

            for malformed in example:
                try:
                    parse_fn(malformed)
                except UnexpectedInput as ut:
                    if ut.state == self.state:
                        try:
                            if ut.token == self.token:  # Try exact match first
                                return label
                        except AttributeError:
                            pass
                        if not candidate:
                            candidate = label

        return candidate 
Example #11
Source File: json_parser.py    From lark with MIT License 6 votes vote down vote up
def __init__(self, terminals, ignore=(), user_callbacks={}):
        assert all(isinstance(t, TerminalDef) for t in terminals), terminals

        terminals = list(terminals)

        # Sanitization
        for t in terminals:
            try:
                re.compile(t.pattern.to_regexp())
            except re.error:
                raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))

            if t.pattern.min_width == 0:
                raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))

        assert set(ignore) <= {t.name for t in terminals}

        # Init
        self.newline_types = [t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp())]
        self.ignore_types = list(ignore)

        terminals.sort(key=lambda x:(-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
        self.terminals = terminals
        self.user_callbacks = user_callbacks
        self.build() 
Example #12
Source File: json_parser.py    From lark with MIT License 6 votes vote down vote up
def lex(self, stream, get_parser_state):
        parser_state = get_parser_state()
        l = _Lex(self.lexers[parser_state], parser_state)
        try:
            for x in l.lex(stream, self.root_lexer.newline_types, self.root_lexer.ignore_types):
                yield x
                parser_state = get_parser_state()
                l.lexer = self.lexers[parser_state]
                l.state = parser_state # For debug only, no need to worry about multithreading
        except UnexpectedCharacters as e:
            # In the contextual lexer, UnexpectedCharacters can mean that the terminal is defined,
            # but not in the current context.
            # This tests the input against the global context, to provide a nicer error.
            root_match = self.root_lexer.match(stream, e.pos_in_stream)
            if not root_match:
                raise

            value, type_ = root_match
            t = Token(type_, value, e.pos_in_stream, e.line, e.column)
            raise UnexpectedToken(t, e.allowed, state=e.state) 
Example #13
Source File: utils.py    From lark with MIT License 6 votes vote down vote up
def get_regexp_width(expr):
    if regex:
        # Since `sre_parse` cannot deal with Unicode categories of the form `\p{Mn}`, we replace these with
        # a simple letter, which makes no difference as we are only trying to get the possible lengths of the regex
        # match here below.
        regexp_final = re.sub(categ_pattern, 'A', expr)
    else:
        if re.search(categ_pattern, expr):
            raise ImportError('`regex` module must be installed in order to use Unicode categories.', expr)
        regexp_final = expr
    try:
        return [int(x) for x in sre_parse.parse(regexp_final).getwidth()]
    except sre_constants.error:
        raise ValueError(expr)

###} 
Example #14
Source File: clues.py    From WAD with GNU General Public License v3.0 6 votes vote down vote up
def read_clues_from_file(filename):
        logging.info("Reading clues file %s", filename)
        try:
            json_data = open(filename)
        except IOError as e:
            logging.error("Error while opening clues file, terminating: %s", tools.error_to_str(e))
            raise

        try:
            if six.PY2:
                clues = json.load(json_data, encoding='utf-8')
            else:
                clues = json.load(json_data)
        except ValueError as e:
            logging.error("Error while reading JSON file, terminating: %s", tools.error_to_str(e))
            raise

        json_data.close()
        categories = dict((k, v['name']) for k, v in six.iteritems(clues['categories']))
        apps = clues['apps']
        return apps, categories 
Example #15
Source File: pyparsing.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __sub__(self, other):
        """Implementation of - operator, returns C{L{And}} with error stop"""
        if isinstance( other, basestring ):
            other = ParserElement.literalStringClass( other )
        if not isinstance( other, ParserElement ):
            warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
                    SyntaxWarning, stacklevel=2)
            return None
        return And( [ self, And._ErrorStop(), other ] ) 
Example #16
Source File: test_re.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_group_name_in_exception(self):
        # Issue 17341: Poor error message when compiling invalid regex
        with self.assertRaisesRegexp(sre_constants.error, '\?foo'):
            re.compile('(?P<?foo>)') 
Example #17
Source File: test_re.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_backref_group_name_in_exception(self):
        # Issue 17341: Poor error message when compiling invalid regex
        with self.assertRaisesRegexp(sre_constants.error, '<foo>'):
            re.compile('(?P=<foo>)') 
Example #18
Source File: test_re.py    From jawfish with MIT License 5 votes vote down vote up
def test_bug_545855(self):
        # bug 545855 -- This pattern failed to cause a compile error as it
        # should, instead provoking a TypeError.
        self.assertRaises(re.error, re.compile, 'foo[a-') 
Example #19
Source File: test_re.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_sre_character_class_literals(self):
        for i in [0, 8, 16, 32, 64, 127, 128, 255]:
            self.assertTrue(re.match(r"[\%03o]" % i, chr(i)))
            self.assertTrue(re.match(r"[\%03o0]" % i, chr(i)))
            self.assertTrue(re.match(r"[\%03o8]" % i, chr(i)))
            self.assertTrue(re.match(r"[\x%02x]" % i, chr(i)))
            self.assertTrue(re.match(r"[\x%02x0]" % i, chr(i)))
            self.assertTrue(re.match(r"[\x%02xz]" % i, chr(i)))
        self.assertRaises(re.error, re.match, "[\911]", "") 
Example #20
Source File: test_re.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_sre_character_literals(self):
        for i in [0, 8, 16, 32, 64, 127, 128, 255]:
            self.assertTrue(re.match(r"\%03o" % i, chr(i)))
            self.assertTrue(re.match(r"\%03o0" % i, chr(i)+"0"))
            self.assertTrue(re.match(r"\%03o8" % i, chr(i)+"8"))
            self.assertTrue(re.match(r"\x%02x" % i, chr(i)))
            self.assertTrue(re.match(r"\x%02x0" % i, chr(i)+"0"))
            self.assertTrue(re.match(r"\x%02xz" % i, chr(i)+"z"))
        self.assertRaises(re.error, re.match, "\911", "") 
Example #21
Source File: test_re.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_symbolic_refs(self):
        self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a', 'xx')
        self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<', 'xx')
        self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g', 'xx')
        self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a a>', 'xx')
        self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<>', 'xx')
        self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<1a1>', 'xx')
        self.assertRaises(IndexError, re.sub, '(?P<a>x)', '\g<ab>', 'xx')
        self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\g<b>', 'xx')
        self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\\2', 'xx')
        self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<-1>', 'xx') 
Example #22
Source File: test_re.py    From jawfish with MIT License 5 votes vote down vote up
def test_group_name_in_exception(self):
        # Issue 17341: Poor error message when compiling invalid regex
        with self.assertRaisesRegex(sre_constants.error, '\?foo'):
            re.compile('(?P<?foo>)') 
Example #23
Source File: test_re.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_sub_template_numeric_escape(self):
        # bug 776311 and friends
        self.assertEqual(re.sub('x', r'\0', 'x'), '\0')
        self.assertEqual(re.sub('x', r'\000', 'x'), '\000')
        self.assertEqual(re.sub('x', r'\001', 'x'), '\001')
        self.assertEqual(re.sub('x', r'\008', 'x'), '\0' + '8')
        self.assertEqual(re.sub('x', r'\009', 'x'), '\0' + '9')
        self.assertEqual(re.sub('x', r'\111', 'x'), '\111')
        self.assertEqual(re.sub('x', r'\117', 'x'), '\117')

        self.assertEqual(re.sub('x', r'\1111', 'x'), '\1111')
        self.assertEqual(re.sub('x', r'\1111', 'x'), '\111' + '1')

        self.assertEqual(re.sub('x', r'\00', 'x'), '\x00')
        self.assertEqual(re.sub('x', r'\07', 'x'), '\x07')
        self.assertEqual(re.sub('x', r'\08', 'x'), '\0' + '8')
        self.assertEqual(re.sub('x', r'\09', 'x'), '\0' + '9')
        self.assertEqual(re.sub('x', r'\0a', 'x'), '\0' + 'a')

        self.assertEqual(re.sub('x', r'\400', 'x'), '\0')
        self.assertEqual(re.sub('x', r'\777', 'x'), '\377')

        self.assertRaises(re.error, re.sub, 'x', r'\1', 'x')
        self.assertRaises(re.error, re.sub, 'x', r'\8', 'x')
        self.assertRaises(re.error, re.sub, 'x', r'\9', 'x')
        self.assertRaises(re.error, re.sub, 'x', r'\11', 'x')
        self.assertRaises(re.error, re.sub, 'x', r'\18', 'x')
        self.assertRaises(re.error, re.sub, 'x', r'\1a', 'x')
        self.assertRaises(re.error, re.sub, 'x', r'\90', 'x')
        self.assertRaises(re.error, re.sub, 'x', r'\99', 'x')
        self.assertRaises(re.error, re.sub, 'x', r'\118', 'x') # r'\11' + '8'
        self.assertRaises(re.error, re.sub, 'x', r'\11a', 'x')
        self.assertRaises(re.error, re.sub, 'x', r'\181', 'x') # r'\18' + '1'
        self.assertRaises(re.error, re.sub, 'x', r'\800', 'x') # r'\80' + '0'

        # in python2.3 (etc), these loop endlessly in sre_parser.py
        self.assertEqual(re.sub('(((((((((((x)))))))))))', r'\11', 'x'), 'x')
        self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\118', 'xyz'),
                         'xz8')
        self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\11a', 'xyz'),
                         'xza') 
Example #24
Source File: pyparsing.py    From Computable with MIT License 5 votes vote down vote up
def __init__( self, pattern, flags=0):
        """The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags."""
        super(Regex,self).__init__()

        if isinstance(pattern, basestring):
            if len(pattern) == 0:
                warnings.warn("null string passed to Regex; use Empty() instead",
                        SyntaxWarning, stacklevel=2)

            self.pattern = pattern
            self.flags = flags

            try:
                self.re = re.compile(self.pattern, self.flags)
                self.reString = self.pattern
            except sre_constants.error:
                warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
                    SyntaxWarning, stacklevel=2)
                raise

        elif isinstance(pattern, Regex.compiledREtype):
            self.re = pattern
            self.pattern = \
            self.reString = str(pattern)
            self.flags = flags
            
        else:
            raise ValueError("Regex may only be constructed with a string or a compiled RE object")

        self.name = _ustr(self)
        self.errmsg = "Expected " + self.name
        self.mayIndexError = False
        self.mayReturnEmpty = True 
Example #25
Source File: pyparsing.py    From Computable with MIT License 5 votes vote down vote up
def __sub__(self, other):
        """Implementation of - operator, returns C{L{And}} with error stop"""
        if isinstance( other, basestring ):
            other = ParserElement.literalStringClass( other )
        if not isinstance( other, ParserElement ):
            warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
                    SyntaxWarning, stacklevel=2)
            return None
        return And( [ self, And._ErrorStop(), other ] ) 
Example #26
Source File: test_re.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_group_name_in_exception(self):
        # Issue 17341: Poor error message when compiling invalid regex
        with self.assertRaisesRegexp(sre_constants.error, '\?foo'):
            re.compile('(?P<?foo>)') 
Example #27
Source File: test_re.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_backref_group_name_in_exception(self):
        # Issue 17341: Poor error message when compiling invalid regex
        with self.assertRaisesRegexp(sre_constants.error, '<foo>'):
            re.compile('(?P=<foo>)') 
Example #28
Source File: pyparsing.py    From jbox with MIT License 5 votes vote down vote up
def __init__( self, pattern, flags=0):
        """The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags."""
        super(Regex,self).__init__()

        if isinstance(pattern, basestring):
            if len(pattern) == 0:
                warnings.warn("null string passed to Regex; use Empty() instead",
                        SyntaxWarning, stacklevel=2)

            self.pattern = pattern
            self.flags = flags

            try:
                self.re = re.compile(self.pattern, self.flags)
                self.reString = self.pattern
            except sre_constants.error:
                warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
                    SyntaxWarning, stacklevel=2)
                raise

        elif isinstance(pattern, Regex.compiledREtype):
            self.re = pattern
            self.pattern = \
            self.reString = str(pattern)
            self.flags = flags
            
        else:
            raise ValueError("Regex may only be constructed with a string or a compiled RE object")

        self.name = _ustr(self)
        self.errmsg = "Expected " + self.name
        self.mayIndexError = False
        self.mayReturnEmpty = True 
Example #29
Source File: test_re.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_sre_character_literals(self):
        for i in [0, 8, 16, 32, 64, 127, 128, 255]:
            self.assertNotEqual(re.match(r"\%03o" % i, chr(i)), None)
            self.assertNotEqual(re.match(r"\%03o0" % i, chr(i)+"0"), None)
            self.assertNotEqual(re.match(r"\%03o8" % i, chr(i)+"8"), None)
            self.assertNotEqual(re.match(r"\x%02x" % i, chr(i)), None)
            self.assertNotEqual(re.match(r"\x%02x0" % i, chr(i)+"0"), None)
            self.assertNotEqual(re.match(r"\x%02xz" % i, chr(i)+"z"), None)
        self.assertRaises(re.error, re.match, "\911", "") 
Example #30
Source File: pyparsing.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __init__( self, pattern, flags=0):
        """The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags."""
        super(Regex,self).__init__()

        if isinstance(pattern, basestring):
            if len(pattern) == 0:
                warnings.warn("null string passed to Regex; use Empty() instead",
                        SyntaxWarning, stacklevel=2)

            self.pattern = pattern
            self.flags = flags

            try:
                self.re = re.compile(self.pattern, self.flags)
                self.reString = self.pattern
            except sre_constants.error:
                warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
                    SyntaxWarning, stacklevel=2)
                raise

        elif isinstance(pattern, Regex.compiledREtype):
            self.re = pattern
            self.pattern = \
            self.reString = str(pattern)
            self.flags = flags
            
        else:
            raise ValueError("Regex may only be constructed with a string or a compiled RE object")

        self.name = _ustr(self)
        self.errmsg = "Expected " + self.name
        self.mayIndexError = False
        self.mayReturnEmpty = True