本文整理匯總了Python中re.compile方法的典型用法代碼示例。如果您正苦於以下問題:Python re.compile方法的具體用法?Python re.compile怎麽用?Python re.compile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類re
的用法示例。
在下文中一共展示了re.compile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: interpolate_url
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def interpolate_url(self):
pattern = r'\{([a-z_]+)\}'
regex = re.compile(pattern)
start = 0
new_url = self.resource_url
while (start + 1) < len(self.resource_url):
match = regex.search(self.resource_url, start)
if match is None:
return new_url
param = match.group(1)
val = getattr(self, param, None)
if val is None:
raise ValueError("Missing variable value")
new_url = new_url.replace('{' + param + '}', str(val))
start = match.end(1) + 1
return new_url
示例2: test_invalid_storage_partitioning
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def test_invalid_storage_partitioning(self, deckhand_ingester,
drydock_state, input_files,
mock_get_build_data):
input_file = input_files.join("invalid_validation.yaml")
design_ref = "file://%s" % str(input_file)
orch = Orchestrator(
state_manager=drydock_state, ingester=deckhand_ingester)
status, site_design = Orchestrator.get_effective_site(orch, design_ref)
validator = StoragePartitioning()
message_list = validator.execute(site_design)
regex = re.compile('Volume group .+ not assigned any physical volumes')
for msg in message_list:
msg = msg.to_dict()
LOG.debug(msg)
assert len(msg.get('documents')) > 0
assert msg.get('error')
assert regex.search(msg.get('message')) is not None
assert len(message_list) == 2
示例3: test_invalid_no_duplicate_IPs
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def test_invalid_no_duplicate_IPs(self, input_files, drydock_state,
deckhand_ingester):
input_file = input_files.join("invalid_validation.yaml")
design_ref = "file://%s" % str(input_file)
orch = Orchestrator(
state_manager=drydock_state, ingester=deckhand_ingester)
status, site_design = Orchestrator.get_effective_site(orch, design_ref)
validator = NoDuplicateIpsCheck()
message_list = validator.execute(site_design)
regex = re.compile('Duplicate IP Address Found: [0-9.]+')
for msg in message_list:
msg = msg.to_dict()
LOG.debug(msg)
assert len(msg.get('documents')) > 0
assert msg.get('error') is True
assert regex.search(msg.get('message')) is not None
示例4: test_invalid_partition_mountpoints
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def test_invalid_partition_mountpoints(self, deckhand_ingester,
drydock_state, input_files,
mock_get_build_data):
input_file = input_files.join("invalid_validation.yaml")
design_ref = "file://%s" % str(input_file)
orch = Orchestrator(
state_manager=drydock_state, ingester=deckhand_ingester)
status, site_design = Orchestrator.get_effective_site(orch, design_ref)
validator = StorageMountpoints()
message_list = validator.execute(site_design, orchestrator=orch)
regex = re.compile('Mountpoint .+ already exists')
for msg in message_list:
msg = msg.to_dict()
LOG.debug(msg)
assert regex.search(msg.get('message')) is not None
assert msg.get('error') is True
示例5: test_invalid_vg_mountpoints
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def test_invalid_vg_mountpoints(self, deckhand_ingester, drydock_state,
input_files, mock_get_build_data):
input_file = input_files.join("invalid_mountpoint.yaml")
design_ref = "file://%s" % str(input_file)
orch = Orchestrator(
state_manager=drydock_state, ingester=deckhand_ingester)
status, site_design = Orchestrator.get_effective_site(orch, design_ref)
validator = StorageMountpoints()
message_list = validator.execute(site_design, orchestrator=orch)
regex = re.compile('Mountpoint .+ already exists')
for msg in message_list:
msg = msg.to_dict()
LOG.debug(msg)
assert regex.search(msg.get('message')) is not None
assert msg.get('error') is True
示例6: test_invalid_boot_storage_small
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def test_invalid_boot_storage_small(self, deckhand_ingester, drydock_state,
input_files, mock_get_build_data):
input_file = input_files.join("invalid_boot_storage_small.yaml")
design_ref = "file://%s" % str(input_file)
orch = Orchestrator(
state_manager=drydock_state, ingester=deckhand_ingester)
status, site_design = Orchestrator.get_effective_site(orch, design_ref)
validator = BootStorageRational()
message_list = validator.execute(site_design, orchestrator=orch)
regex = re.compile('.+ volume must be > .+GB')
for msg in message_list:
msg = msg.to_dict()
LOG.debug(msg)
assert len(msg.get('documents')) > 0
assert regex.search(msg.get('message')) is not None
assert msg.get('error')
assert len(message_list) == 4
示例7: test_invalid_network_cidr
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def test_invalid_network_cidr(self, mocker, deckhand_ingester,
drydock_state, input_files):
input_file = input_files.join("invalid_network_cidr.yaml")
design_ref = "file://%s" % str(input_file)
orch = Orchestrator(
state_manager=drydock_state, ingester=deckhand_ingester)
status, site_design = Orchestrator.get_effective_site(orch, design_ref)
validator = CidrValidity()
message_list = validator.execute(site_design, orchestrator=orch)
msg = message_list[0].to_dict()
regex_diagnostic = re.compile('Provide a CIDR acceptable by MAAS: .+')
regex_message = re.compile('The provided CIDR .+ has host bits set')
assert len(message_list) >= 1
assert msg.get('error') is True
assert any([
regex_diagnostic.search(msg.get('diagnostic')),
regex_message.search(msg.get('message'))
])
示例8: convert_param
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [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
示例9: _parse_summary
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def _parse_summary(self):
"""Grab signature (if given) and summary"""
summary = self._doc.read_to_next_empty_line()
summary_str = "\n".join([s.strip() for s in summary])
if re.compile('^([\\w. ]+=)?[\\w\\.]+\\(.*\\)$').match(summary_str):
self['Signature'] = summary_str
if not self._is_at_section():
self['Summary'] = self._doc.read_to_next_empty_line()
elif re.compile('^[\\w]+\n[-]+').match(summary_str):
self['Summary'] = ''
self._doc.reset()
else:
self['Summary'] = summary
if not self._is_at_section():
self['Extended Summary'] = self._read_to_next_section()
示例10: format_pixiv_illust_original_url
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def format_pixiv_illust_original_url(id_url, mode=1):
tag = 'Format_Pixiv_Illust_Original_Url'
if mode == 1:
contents = get_text_from_url(id_url)
try:
img_src_re = re.compile(r'\"urls\":{.*?}')
img_src = img_src_re.findall(contents)
final_dict = json.loads("{" + img_src[0] + "}")
return final_dict['urls']['original']
except Exception as e:
print_with_tag(tag, "An error occurred when parsing the json file.")
print_with_tag(tag, e)
elif mode == 2:
data_list = []
json_datas = get_text_from_url(id_url)
json_datas_format = json.loads(json_datas)['body']
for urls in json_datas_format:
data_list.append(urls['urls']['original'])
return data_list
示例11: tweak
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def tweak(self, content):
tweaked = self.legacy_tweak(content)
if tweaked:
return tweaked
apply_persistence_to_all_lines = \
0 < self.setup_params.persistence_size and \
not self.config_is_persistence_aware(content)
matching_re = r'^(\s*(%s)\s*)(.*)$' % self.BOOT_PARAMS_STARTER
kernel_parameter_line_pattern = re.compile(
matching_re,
flags = re.I | re.MULTILINE)
out = self.tweak_first_match(
content,
kernel_parameter_line_pattern,
apply_persistence_to_all_lines,
self.param_operations(),
self.param_operations_for_persistence())
return self.post_process(out)
示例12: _match_major_minor
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def _match_major_minor(cls, value):
"""
Match the number under the assumption that it is a major,minor pair.
:param str value: value to match
:returns: the device number or None
:rtype: int or NoneType
"""
major_minor_re = re.compile(
r'^(?P<major>\d+)(\D+)(?P<minor>\d+)$'
)
match = major_minor_re.match(value)
return match and os.makedev(
int(match.group('major')),
int(match.group('minor'))
)
示例13: escape_wikitext
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def escape_wikitext(wikitext):
"""Escape wikitext for use in file description."""
rep = OrderedDict([
('{|', '{{(}}|'),
('|}', '|{{)}}'),
('||', '||'),
('|', '|'),
('[[', '{{!((}}'),
(']]', '{{))!}}'),
('{{', '{{((}}'),
('}}', '{{))}}'),
('{', '{{(}}'),
('}', '{{)}}'),
])
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
pattern = re.compile("|".join(rep.keys()))
return pattern.sub(lambda m: rep[re.escape(m.group(0))], wikitext)
# Source: mediawiki.Title.js@9df363d
示例14: __init__
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def __init__(self, interval, stat_func=None, pattern='.*', sort=False):
if stat_func is None:
def asum_stat(x):
"""returns |x|/size(x), async execution."""
return ndarray.norm(x)/sqrt(x.size)
stat_func = asum_stat
self.stat_func = stat_func
self.interval = interval
self.activated = False
self.queue = []
self.step = 0
self.exes = []
self.re_prog = re.compile(pattern)
self.sort = sort
def stat_helper(name, array):
"""wrapper for executor callback"""
array = ctypes.cast(array, NDArrayHandle)
array = NDArray(array, writable=False)
if not self.activated or not self.re_prog.match(py_str(name)):
return
self.queue.append((self.step, py_str(name), self.stat_func(array)))
self.stat_helper = stat_helper
示例15: _collect_params_with_prefix
# 需要導入模塊: import re [as 別名]
# 或者: from re import compile [as 別名]
def _collect_params_with_prefix(self, prefix=''):
if prefix:
prefix += '.'
pattern = re.compile(r'(l|r)(\d)_(i2h|h2h)_(weight|bias)\Z')
def convert_key(m, bidirectional): # for compatibility with old parameter format
d, l, g, t = [m.group(i) for i in range(1, 5)]
if bidirectional:
return '_unfused.{}.{}_cell.{}_{}'.format(l, d, g, t)
else:
return '_unfused.{}.{}_{}'.format(l, g, t)
bidirectional = any(pattern.match(k).group(1) == 'r' for k in self._reg_params)
ret = {prefix + convert_key(pattern.match(key), bidirectional) : val
for key, val in self._reg_params.items()}
for name, child in self._children.items():
ret.update(child._collect_params_with_prefix(prefix + name))
return ret