本文整理匯總了Python中sre_constants.error方法的典型用法代碼示例。如果您正苦於以下問題:Python sre_constants.error方法的具體用法?Python sre_constants.error怎麽用?Python sre_constants.error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sre_constants
的用法示例。
在下文中一共展示了sre_constants.error方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_sre_character_class_literals
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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]", "")
示例2: test_symbolic_groups
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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.))')
示例3: test_other_escapes
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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'))
示例4: rm
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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
示例5: mput
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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)
示例6: mget
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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)
示例7: match_examples
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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
示例8: __init__
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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()
示例9: lex
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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)
示例10: get_regexp_width
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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)
###}
示例11: read_clues_from_file
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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
示例12: compile_clues
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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)
示例13: regex_validator
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
def regex_validator(args, state):
with open(args.checks, "r") as fd:
for line in fd.read().splitlines():
if line.startswith("#") or len(line) == 0:
continue
try:
re.subn(line, r'\1', "Expression test")
except sre_constants.error as e:
print(bcolors.FAIL + "Invalid Regular expression:\n\t" + line)
if "group" in str(e):
print(
"Ensure expression contains"
"a capture group for matches:\n\t" + str(e))
sys.exit(-1)
state.checks.append(line)
split = []
if not (state.query[0] == "\"" and state.query[-1] == "\""):
split = re.split(GITHUB_WHITESPACE, state.query)
for part in [state.query] + split:
if part:
escaped_query = re.escape(part) if split else \
part.replace("\"", "")
state.checks.append("(?i)(" + escaped_query + ")")
return state
示例14: test_sub_template_numeric_escape
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
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')
示例15: test_sre_character_literals
# 需要導入模塊: import sre_constants [as 別名]
# 或者: from sre_constants import error [as 別名]
def test_sre_character_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"\%03o" % i, chr(i)))
self.assertIsNotNone(re.match(r"\%03o0" % i, chr(i)+"0"))
self.assertIsNotNone(re.match(r"\%03o8" % i, chr(i)+"8"))
self.assertIsNotNone(re.match(r"\x%02x" % i, chr(i)))
self.assertIsNotNone(re.match(r"\x%02x0" % i, chr(i)+"0"))
self.assertIsNotNone(re.match(r"\x%02xz" % i, chr(i)+"z"))
if i < 0x10000:
self.assertIsNotNone(re.match(r"\u%04x" % i, chr(i)))
self.assertIsNotNone(re.match(r"\u%04x0" % i, chr(i)+"0"))
self.assertIsNotNone(re.match(r"\u%04xz" % i, chr(i)+"z"))
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"\0", "\000"))
self.assertIsNotNone(re.match(r"\08", "\0008"))
self.assertIsNotNone(re.match(r"\01", "\001"))
self.assertIsNotNone(re.match(r"\018", "\0018"))
self.assertIsNotNone(re.match(r"\567", chr(0o167)))
self.assertRaises(re.error, re.match, r"\911", "")
self.assertRaises(re.error, re.match, r"\x1", "")
self.assertRaises(re.error, re.match, r"\x1z", "")
self.assertRaises(re.error, re.match, r"\u123", "")
self.assertRaises(re.error, re.match, r"\u123z", "")
self.assertRaises(re.error, re.match, r"\U0001234", "")
self.assertRaises(re.error, re.match, r"\U0001234z", "")
self.assertRaises(re.error, re.match, r"\U00110000", "")