本文整理匯總了Python中re.error方法的典型用法代碼示例。如果您正苦於以下問題:Python re.error方法的具體用法?Python re.error怎麽用?Python re.error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類re
的用法示例。
在下文中一共展示了re.error方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_tokens
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def get_tokens(self):
tokens = self.ldict.get("tokens",None)
if not tokens:
self.log.error("No token list is defined")
self.error = 1
return
if not isinstance(tokens,(list, tuple)):
self.log.error("tokens must be a list or tuple")
self.error = 1
return
if not tokens:
self.log.error("tokens is empty")
self.error = 1
return
self.tokens = tokens
# Validate the tokens
示例2: test_sre_character_class_literals
# 需要導入模塊: import re [as 別名]
# 或者: from re 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]", "")
示例3: run
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def run(self):
q = self.processed_query()
sent_pos, i, sent_count = [], 0, 0
for sent in self.model.tagged_sents[self.model.last_sent_searched:]:
try:
m = re.search(q, sent)
except re.error:
self.model.reset_results()
self.model.queue.put(SEARCH_ERROR_EVENT)
return
if m:
sent_pos.append((sent, m.start(), m.end()))
i += 1
if i > self.count:
self.model.last_sent_searched += sent_count - 1
break
sent_count += 1
if (self.count >= len(sent_pos)):
self.model.last_sent_searched += sent_count - 1
self.model.last_page = self.page
self.model.set_results(self.page, sent_pos)
else:
self.model.set_results(self.page, sent_pos[:-1])
self.model.queue.put(SEARCH_TERMINATED_EVENT)
示例4: __call__
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def __call__(self, value):
if value is None:
return value
path = six.text_type(value)
if not os.path.isabs(path):
path = os.path.join(self.directory, path)
try:
value = open(path, self.mode) if self.buffering is None else open(path, self.mode, self.buffering)
except IOError as error:
raise ValueError('Cannot open {0} with mode={1} and buffering={2}: {3}'.format(
value, self.mode, self.buffering, error))
return value
示例5: get_tokens
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def get_tokens(self):
tokens = self.ldict.get('tokens', None)
if not tokens:
self.log.error('No token list is defined')
self.error = True
return
if not isinstance(tokens, (list, tuple)):
self.log.error('tokens must be a list or tuple')
self.error = True
return
if not tokens:
self.log.error('tokens is empty')
self.error = True
return
self.tokens = tokens
# Validate the tokens
示例6: checks
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def checks(self, format, raises=()):
"""
Register a decorated function as validating a new format.
Arguments:
format (str):
The format that the decorated function will check.
raises (Exception):
The exception(s) raised by the decorated function when
an invalid instance is found.
The exception object will be accessible as the
:attr:`ValidationError.cause` attribute of the resulting
validation error.
"""
def _checks(func):
self.checkers[format] = (func, raises)
return func
return _checks
示例7: __call__
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def __call__(self, value):
if value is None or isinstance(value, list):
return value
try:
value = next(csv.reader([value], self.Dialect))
except csv.Error as error:
raise ValueError(error)
if self._validator is None:
return value
try:
for index, item in enumerate(value):
value[index] = self._validator(item)
except ValueError as error:
raise ValueError('Could not convert item {}: {}'.format(index, error))
return value
示例8: __init__
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def __init__(self, url_rule, view_func, name, options):
self._name = name
self._url_rule = url_rule
self._view_func = view_func
self._options = options or {}
self._keywords = re.findall(r'\<(.+?)\>', url_rule)
#change <> to {} for use with str.format()
self._url_format = self._url_rule.replace('<', '{').replace('>', '}')
# Make a regex pattern for matching incoming URLs
rule = self._url_rule
if rule != '/':
# Except for a path of '/', the trailing slash is optional.
rule = self._url_rule.rstrip('/') + '/?'
p = rule.replace('<', '(?P<').replace('>', '>[^/]+?)')
try:
self._regex = re.compile('^' + p + '$')
except re.error, e:
raise ValueError, ('There was a problem creating this URL rule. '
'Ensure you do not have any unpaired angle '
'brackets: "<" or ">"')
示例9: _error
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def _error(self, url, item, *_args):
"""Callback when a download error occurred.
Args:
url: The original url of the asset as QUrl.
item: The DownloadItem given by the DownloadManager.
"""
assert self.writer is not None
try:
self.pending_downloads.remove((url, item))
except KeyError:
# This might happen if .collect_zombies() calls .finished() and the
# error handler will be called after .collect_zombies
log.downloads.debug("Oops! Download already gone: {}".format(item))
return
item.fileobj.actual_close()
# Add a stub file, see comment in .fetch_url() for more information
self.writer.add_file(urlutils.encoded_url(url), b'')
if self.pending_downloads:
return
self._finish_file()
示例10: checks
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def checks(self, format, raises=()):
"""
Register a decorated function as validating a new format.
:argument str format: the format that the decorated function will check
:argument Exception raises: the exception(s) raised by the decorated
function when an invalid instance is found. The exception object
will be accessible as the :attr:`ValidationError.cause` attribute
of the resulting validation error.
"""
def _checks(func):
self.checkers[format] = (func, raises)
return func
return _checks
示例11: regex
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def regex(ioc_type):
ioc_patts = {
"ip":b"((?:(?:[12]\d?\d?|[1-9]\d|[1-9])(?:\[\.\]|\.)){3}(?:[12]\d?\d?|[\d+]{1,2}))",
"domain":b"([A-Za-z0-9]+(?:[\-|\.][A-Za-z0-9]+)*(?:\[\.\]|\.)(?:com|net|edu|ru|org|de|uk|jp|br|pl|info|fr|it|cn|in|su|pw|biz|co|eu|nl|kr|me))",
"md5":b"\W([A-Fa-f0-9]{32})(?:\W|$)",
"sha1":b"\W([A-Fa-f0-9]{40})(?:\W|$)",
"sha256":b"\W([A-Fa-f0-9]{64})(?:\W|$)",
"email":b"[a-zA-Z0-9_]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?!([a-zA-Z0-9]*\.[a-zA-Z0-9]*\.[a-zA-Z0-9]*\.))(?:[A-Za-z0-9](?:[a-zA-Z0-9-]*[A-Za-z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?",
"URL":b"((?:http|ftp|https)\:\/\/(?:[\w+?\.\w+])+[a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;]+)",
"yara":b"(rule\s[\w\W]{,30}\{[\w\W\s]*\})"
}
try:
pattern = re.compile(ioc_patts[ioc_type])
except re.error:
print('[!] Invalid type specified.')
sys.exit(0)
return pattern
示例12: update_progress
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def update_progress(progress):
barLength = 20 # Modify this value to change the length of the progress bar
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0:
progress = 0
status = Fore.RED + "Halt!\r\n"
if progress >= .999:
progress = 1
status = Fore.GREEN + " Complete!\r\n"
block = int(round(barLength*progress))
text = "\r[*] Progress: [{0}] {1}% {2}".format("#"*block + "-"*(barLength-block), round(progress*100), status)
sys.stdout.write(text)
sys.stdout.flush()
示例13: _msg_grammar
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def _msg_grammar(self, msg):
''' Return only message if grammar is not defined. Return regex if grammar is defined. And None if no match'''
if self.mention:
msg = self._remove_bot_id(msg, self.bot_id)
if not self.grammar or not msg:
# No grammar rule or or no mention of the bot, Just return msg
return msg
try:
regex = re.compile(r"{}".format(self.grammar))
except re.error as regex_error:
fail_unless(False, "The grammar expression '{}' has an error : {}".format(self.grammar, regex_error))
return regex.match(msg)
示例14: new_query_new_thread
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def new_query_new_thread(self, input_text):
if not self.setting_params['fts'] or self.setting_params['regex_mode']:
self.status_bar.showMessage(' ...')
if input_text == '' and self.regex_query_ready:
self.show_first_500()
return
if self.setting_params['regex_mode']:
try:
re.compile(input_text)
is_valid = True
except re.error:
is_valid = False
if not is_valid:
self.status_bar.showMessage('regex not valid')
return
self.queries_threads.append(
{'input': input_text,
'thread': ThreadDBQuery(input_text, self.setting_params)})
self.queries_threads[-1]['thread'].db_query_signal.connect(
self.database_query_done, Qc.Qt.QueuedConnection)
if self.regex_query_ready:
self.queries_threads[-1]['thread'].start()
self.regex_query_ready = False
else:
self.queries_threads.append(
{'input': input_text,
'thread': ThreadDBQuery(input_text, self.setting_params)})
self.queries_threads[-1]['thread'].db_query_signal.connect(
self.database_query_done, Qc.Qt.QueuedConnection)
self.queries_threads[-1]['thread'].start()
if len(self.queries_threads) > 100:
del self.queries_threads[0:80]
# CHECK IF THE RESULTS COME FROM THE LAST ONE OR THERE ARE SOME STILL GOING
示例15: error
# 需要導入模塊: import re [as 別名]
# 或者: from re import error [as 別名]
def error(self,msg,*args,**kwargs):
self.f.write("ERROR: " + (msg % args) + "\n")