| 30 | |
| 31 | |
| 32 | class RegexObject(object): |
| 33 | |
| 34 | def __init__(self, pattern, flags=0, **options): |
| 35 | if isinstance(pattern, bytes): |
| 36 | raise TypeError("'rure.regex.RegexObject' must be instantiated with" |
| 37 | " a unicode object as first argument.") |
| 38 | |
| 39 | self.flags = flags |
| 40 | self.pattern = pattern.encode('utf8') |
| 41 | self.options = options |
| 42 | self.submatches = options.pop('submatches', False) |
| 43 | |
| 44 | self.rure_flags = DEFAULT_FLAGS |
| 45 | for flag, rure_flag in FLAG_MAP.items(): |
| 46 | if flags & flag: |
| 47 | if rure_flag is None: |
| 48 | msg = u"rure doesn't support the flag '%s'" |
| 49 | warnings.warn(msg % FLAG_NAMES[flag], SyntaxWarning) |
| 50 | else: |
| 51 | self.rure_flags = self.rure_flags | rure_flag |
| 52 | |
| 53 | self._rure = Rure(self.pattern, flags=self.rure_flags, **self.options) |
| 54 | self._match_rure = None |
| 55 | self._match_rure_pos = None |
| 56 | |
| 57 | names = [name for name in self.capture_names()] |
| 58 | # This can be greater than len(self.groupindex) due to |
| 59 | # unnamed groupes |
| 60 | self.groups = len(names) |
| 61 | self.groupindex = { |
| 62 | name: pos |
| 63 | for pos, name in enumerate(names) |
| 64 | if name is not None |
| 65 | } |
| 66 | |
| 67 | def capture_names(self): |
| 68 | return self._rure.capture_names() |
| 69 | |
| 70 | @accepts_string |
| 71 | def is_match(self, string, pos=0, endpos=None): |
| 72 | haystack = string[:endpos].encode('utf8') |
| 73 | return self._rure.is_match(haystack, pos) |
| 74 | |
| 75 | @accepts_string |
| 76 | def search(self, string, pos=0, endpos=None): |
| 77 | haystack = string[:endpos].encode('utf8') |
| 78 | if self.submatches: |
| 79 | captures = self._rure.captures(haystack, pos) |
| 80 | if captures: |
| 81 | return MatchObject(pos, endpos, self, haystack, captures) |
| 82 | else: |
| 83 | match = self._rure.find(haystack, pos) |
| 84 | if match: |
| 85 | return MatchObject(pos, endpos, self, haystack, 0) |
| 86 | |
| 87 | @accepts_string |
| 88 | def match(self, string, pos=0, endpos=None): |
| 89 | if self._match_rure is None or pos != self._match_rure_pos: |