本文整理汇总了Python中re.search方法的典型用法代码示例。如果您正苦于以下问题:Python re.search方法的具体用法?Python re.search怎么用?Python re.search使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类re
的用法示例。
在下文中一共展示了re.search方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_render_debug_better_error_message_recursion_error_with_multiple_duplicated_frames
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def test_render_debug_better_error_message_recursion_error_with_multiple_duplicated_frames():
io = BufferedIO()
io.set_verbosity(VERBOSE)
with pytest.raises(RecursionError) as e:
first()
trace = ExceptionTrace(e.value)
trace.render(io)
expected = r"... Previous 2 frames repeated \d+ times".format(
filename=re.escape(trace._get_relative_file_path(__file__)),
)
assert re.search(expected, io.fetch_output()) is not None
示例2: matchHeader
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def matchHeader(self, headermatch, attack=False):
if attack:
r = self.attackres
else: r = rq
if r is None:
return
header, match = headermatch
headerval = r.headers.get(header)
if headerval:
# set-cookie can have multiple headers, python gives it to us
# concatinated with a comma
if header == 'Set-Cookie':
headervals = headerval.split(', ')
else:
headervals = [headerval]
for headerval in headervals:
if re.search(match, headerval, re.I):
return True
return False
示例3: get_stock_price
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def get_stock_price(self, symbol):
"""
获取股票当前价格
:param symbol:
:return:
"""
url = "http://hq.sinajs.cn/list=s_%s" % symbol
r = self.session.get(url)
m = re.search(r'"(.*)"', r.text)
if m and m.groups()[0]:
name, price, _, _, _, _ = m.groups()[0].split(',')
logger.info("股票[%s](%s)当前价格为: %s" % (name, symbol, price))
return price
else:
logger.error("获取股票%s当前价格失败" % symbol)
raise StockMatchError()
# fixme: 该方法暂时只支持买入A股,不支持操作美股和港股
示例4: call
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def call(self, cmd, **kwargs):
print('Running "{}"'.format(cmd), file=sys.stderr)
expect = kwargs.pop("expect", [dict(return_codes=[os.EX_OK], stdout=None, stderr=None)])
process = subprocess.Popen(cmd, stdin=kwargs.get("stdin", subprocess.PIPE), stdout=subprocess.PIPE,
stderr=subprocess.PIPE, **kwargs)
out, err = process.communicate()
return_code = process.poll()
out = out.decode(sys.stdin.encoding)
err = err.decode(sys.stdin.encoding)
def match(return_code, out, err, expected):
exit_ok = return_code in expected["return_codes"]
stdout_ok = re.search(expected.get("stdout") or "", out)
stderr_ok = re.search(expected.get("stderr") or "", err)
return exit_ok and stdout_ok and stderr_ok
if not any(match(return_code, out, err, exp) for exp in expect):
print(err)
e = subprocess.CalledProcessError(return_code, cmd, output=out)
e.stdout, e.stderr = out, err
raise e
return self.SubprocessResult(out, err, return_code)
示例5: read_process
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def read_process(cmd, args=''):
fullcmd = '%s %s' % (cmd, args)
pipeout = popen(fullcmd)
try:
firstline = pipeout.readline()
cmd_not_found = re.search(
b'(not recognized|No such file|not found)',
firstline,
re.IGNORECASE
)
if cmd_not_found:
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
finally:
pipeout.close()
return output
示例6: convert_param
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def convert_param(method, param):
# remove notation, split by upper, convert to lowercase
param_sanitized = param.replace('*', '')
substr = param_sanitized
try:
substr = re.search('([A-Z]\w+)', param_sanitized).group(1)
except:
pass
case_re = re.compile(r'((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
converted_param = case_re.sub(r'_\1', substr).lower()
if converted_param in keyword.kwlist or converted_param in dir(__builtins__):
converted_param += '_param'
# check for duplicates. if seen, append number to end
if 'params' in method and len([param for param in method['params'] if param['name'] == converted_param]):
param_names = [param['name'] for param in method['params']]
for x in range(2, 10):
count_name = '{:s}{:d}'.format(converted_param, x)
if count_name not in param_names:
converted_param = count_name
break
return converted_param
示例7: find_version
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def find_version(*file_paths):
# Open in Latin-1 so that we avoid encoding errors.
# Use codecs.open for Python 2 compatibility
try:
f = codecs.open(os.path.join(here, *file_paths), 'r', 'latin1')
version_file = f.read()
f.close()
except:
raise RuntimeError("Unable to find version string.")
# The version line must have the form
# __version__ = 'ver'
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
# Get the long description from the relevant file
示例8: writeDir_r
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def writeDir_r(self, det_dir, dire, pp, r, all_type):
#gen.log "writeDir_r:(%s)"%(det_dir)
dirs = self.readDirItems(dire.locExtent, dire.lenData)
for d in dirs:
if not d.fIdentifier in [".", ".."]:
if (pp != None) and (pp.search(d.fIdentifier) == None):
match = False
else:
match = True
#gen.log "mathing %s, %s, (%x)"%(match, d.fIdentifier, d.fFlag)
p = det_dir + "/" + d.fIdentifier
if d.fFlag & 0x02 == 0x02:
if not os.path.exists(p):
os.makedirs(p, 0o777)
if r:
if match:
self.writeDir_r(p, d, None, r, all_type) # Don't need to match subdirectory.
else:
self.writeDir_r(p, d, pp, r, all_type)
elif match:
self.writeFile(d, p, all_type)
# if not d.fIdentifier end #
# for d in dirs end #
示例9: test_zero_prop
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def test_zero_prop():
data = mx.symbol.Variable('data')
for i in range(10):
data = data * data
exe = data.simple_bind(ctx=mx.cpu(), data=(10, 3, 256, 256))
big = int(re.search('Total (\d+) MB allocated', exe.debug_str()).group(1))
exe = data.simple_bind(ctx=mx.cpu(), data=(10, 3, 256, 256), grad_req='null')
small1 = int(re.search('Total (\d+) MB allocated', exe.debug_str()).group(1))
data = mx.sym.stop_gradient(data)
exe = data.simple_bind(ctx=mx.cpu(), data=(10, 3, 256, 256))
small2 = int(re.search('Total (\d+) MB allocated', exe.debug_str()).group(1))
assert big > small2
assert small1 == small2
示例10: remove_consecutive
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def remove_consecutive(self, ner_tags, ner_values):
for i in range(len(ner_tags)):
if ((ner_tags[i] == "NUMBER" or ner_tags[i] == "MONEY" or
ner_tags[i] == "PERCENT" or ner_tags[i] == "DATE") and
i + 1 < len(ner_tags) and ner_tags[i] == ner_tags[i + 1] and
ner_values[i] == ner_values[i + 1] and ner_values[i] != ""):
word = ner_values[i]
word = word.replace(">", "").replace("<", "").replace("=", "").replace(
"%", "").replace("~", "").replace("$", "").replace("£", "").replace(
"€", "")
if (re.search("[A-Z]", word) and not (is_date(word)) and not (
self.is_money(word))):
ner_values[i] = "A"
else:
ner_values[i] = ","
return ner_tags, ner_values
示例11: is_binary_file
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def is_binary_file(filename, file_content):
if filename is None:
return False
else:
try:
extension = re.search(r'.*\.([^\.]+)$', filename).groups()[0]
except AttributeError:
extension = None
if extension in binary_extensions:
return True
else:
try:
file_content.encode('utf-8', errors='strict')
except UnicodeEncodeError:
return True
else:
return False
示例12: _do_use_weight_decay
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def _do_use_weight_decay(self, param_name):
"""Whether to use L2 weight decay for `param_name`."""
if not self.weight_decay_rate:
return False
if self.exclude_from_weight_decay:
for r in self.exclude_from_weight_decay:
if re.search(r, param_name) is not None:
return False
return True
示例13: get_version
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def get_version(string):
""" Parse the version number variable __version__ from a script. """
import re
version_re = r"^__version__ = ['\"]([^'\"]*)['\"]"
version_str = re.search(version_re, string, re.M).group(1)
return version_str
示例14: find_meta
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def find_meta(meta):
"""
Extract __*meta*__ from META_FILE.
"""
meta_match = re.search(r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))
# -- Project information -----------------------------------------------------
示例15: find_meta
# 需要导入模块: import re [as 别名]
# 或者: from re import search [as 别名]
def find_meta(meta):
"""
Extract __*meta*__ from META_FILE.
"""
meta_match = re.search(r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))