本文整理汇总了Python中re.fullmatch方法的典型用法代码示例。如果您正苦于以下问题:Python re.fullmatch方法的具体用法?Python re.fullmatch怎么用?Python re.fullmatch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类re
的用法示例。
在下文中一共展示了re.fullmatch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: expand_windows_drive
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def expand_windows_drive(path: str) -> str:
r"""Expand a drive-path like E: into E:\.
Does nothing for other paths.
Args:
path: The path to expand.
"""
# Usually, "E:" on Windows refers to the current working directory on drive
# E:\. The correct way to specifify drive E: is "E:\", but most users
# probably don't use the "multiple working directories" feature and expect
# "E:" and "E:\" to be equal.
if re.fullmatch(r'[A-Z]:', path, re.IGNORECASE):
return path + "\\"
else:
return path
示例2: _parse_arg_inside
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def _parse_arg_inside(self, line: str) -> bool:
"""Parse subsequent argument lines."""
argname = self._cur_arg_name
assert argname is not None
descs = self.arg_descs[argname]
assert isinstance(descs, list)
if re.fullmatch(r'[A-Z][a-z]+:', line):
if not descs[-1].strip():
del descs[-1]
return True
elif not line.strip():
descs.append('\n\n')
elif line[4:].startswith(' '):
descs.append(line.strip() + '\n')
else:
self._process_arg(line)
return False
示例3: to_py
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def to_py(self, value: _StrUnset) -> _StrUnsetNone:
self._basic_py_validation(value, str)
if isinstance(value, usertypes.Unset):
return value
elif not value:
return None
self._validate_encoding(value)
self._validate_valid_values(value)
if self.forbidden is not None and any(c in value
for c in self.forbidden):
raise configexc.ValidationError(value, "may not contain the chars "
"'{}'".format(self.forbidden))
if self.minlen is not None and len(value) < self.minlen:
raise configexc.ValidationError(value, "must be at least {} chars "
"long!".format(self.minlen))
if self.maxlen is not None and len(value) > self.maxlen:
raise configexc.ValidationError(value, "must be at most {} chars "
"long!".format(self.maxlen))
if self.regex is not None and not re.fullmatch(self.regex, value):
raise configexc.ValidationError(value, "does not match {}"
.format(self.regex))
return value
示例4: on_attributes_update
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def on_attributes_update(self, content):
try:
for attribute_request in self.__attribute_updates:
if fullmatch(attribute_request["deviceNameFilter"], content["device"]) and fullmatch(attribute_request["attributeFilter"], list(content["data"].keys())[0]):
converted_data = attribute_request["converter"].convert(attribute_request, content)
response_queue = Queue(1)
request_dict = {"config": {**attribute_request,
**converted_data},
"request": request}
attribute_update_request_thread = Thread(target=self.__send_request,
args=(request_dict, response_queue, log),
daemon=True,
name="Attribute request to %s" % (converted_data["url"]))
attribute_update_request_thread.start()
attribute_update_request_thread.join()
if not response_queue.empty():
response = response_queue.get_nowait()
log.debug(response)
del response_queue
except Exception as e:
log.exception(e)
示例5: server_side_rpc_handler
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def server_side_rpc_handler(self, content):
try:
for rpc_request in self.__rpc_requests:
if fullmatch(rpc_request["deviceNameFilter"], content["device"]) and fullmatch(rpc_request["methodFilter"], content["data"]["method"]):
converted_data = rpc_request["converter"].convert(rpc_request, content)
response_queue = Queue(1)
request_dict = {"config": {**rpc_request,
**converted_data},
"request": request}
request_dict["config"].get("uplink_converter")
rpc_request_thread = Thread(target=self.__send_request,
args=(request_dict, response_queue, log),
daemon=True,
name="RPC request to %s" % (converted_data["url"]))
rpc_request_thread.start()
rpc_request_thread.join()
if not response_queue.empty():
response = response_queue.get_nowait()
log.debug(response)
self.__gateway.send_rpc_reply(device=content["device"], req_id=content["data"]["id"], content=response[2])
self.__gateway.send_rpc_reply(success_sent=True)
del response_queue
except Exception as e:
log.exception(e)
示例6: convert
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def convert(self, config, data):
device_name = self.__config["deviceName"]
result = {"deviceName": device_name,
"deviceType": self.__config.get("deviceType", "OPC-UA Device"),
"attributes": [],
"telemetry": [], }
try:
information_types = {"attributes": "attributes", "timeseries": "telemetry"}
for information_type in information_types:
for information in self.__config[information_type]:
path = TBUtility.get_value(information["path"], get_tag=True)
if isinstance(config, tuple):
config_information = config[0].replace('\\\\', '\\') if path == config[0].replace('\\\\', '\\') or fullmatch(path, config[0].replace('\\\\', '\\')) else config[1].replace('\\\\', '\\')
else:
config_information = config.replace('\\\\', '\\')
if path == config_information or fullmatch(path, config_information) or path.replace('\\\\', '\\') == config_information:
result[information_types[information_type]].append({information["key"]: information["path"].replace("${"+path+"}", str(data))})
return result
except Exception as e:
log.exception(e)
示例7: on_attributes_update
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def on_attributes_update(self, content):
try:
for attribute_request in self.__attribute_updates:
if fullmatch(attribute_request["deviceNameFilter"], content["device"]) and \
fullmatch(attribute_request["attributeFilter"], list(content["data"].keys())[0]):
converted_data = attribute_request["downlink_converter"].convert(attribute_request, content)
response_queue = Queue(1)
request_dict = {"config": {**attribute_request,
**converted_data},
"request": regular_request}
with self._app.test_request_context():
attribute_update_request_thread = Thread(target=self.__send_request,
args=(request_dict, response_queue, log),
daemon=True,
name="Attribute request to %s" % (converted_data["url"]))
attribute_update_request_thread.start()
attribute_update_request_thread.join()
if not response_queue.empty():
response = response_queue.get_nowait()
log.debug(response)
del response_queue
except Exception as e:
log.exception(e)
示例8: started_event
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def started_event(self, ex_info, command, host_info, start_time, config, meta_info, _id):
prefix = config['dataset']
if config['run_descr']:
prefix += '-' + config['run_descr']
def existing_run_nrs():
pattern = '{}(-\d+)?'.format(prefix)
run_dirs = (d for d in os.listdir(self.basedir)
if os.path.isdir(os.path.join(self.basedir, d)))
for run_dir in run_dirs:
match = re.fullmatch(pattern, run_dir)
if match:
num_str = match.group(1)
yield int(num_str[1:] if num_str else 0)
max_nr = max(existing_run_nrs(), default=None)
if max_nr is None:
return prefix
else:
return prefix + '-{}'.format(max_nr + 1)
示例9: read_meta_data
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def read_meta_data(md_file):
"""
Reads the spkike glx metadata file and parse in a dictionary
Agnostic: does not make any assumption on the keys/content, it just parses key=values
:param md_file: last sample to be read, python slice-wise
:return: Data array, sync trace, meta-data
"""
with open(md_file) as fid:
md = fid.read()
d = {}
for a in md.splitlines():
k, v = a.split('=')
# if all numbers, try to interpret the string
if v and re.fullmatch('[0-9,.]*', v) and v.count('.') < 2:
v = [float(val) for val in v.split(',')]
# scalars should not be nested
if len(v) == 1:
v = v[0]
# tildes in keynames removed
d[k.replace('~', '')] = v
d['neuropixelVersion'] = _get_neuropixel_version_from_meta(d)
d['serial'] = _get_serial_number_from_meta(d)
return Bunch(d)
示例10: replace_emoji
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def replace_emoji(text: str, client: Client) -> str:
if text is None:
return ''
output = text
symbols = re.findall(r'\{([A-Z0-9/]{1,3})\}', text)
for symbol in symbols:
name = symbol
name = name.replace('/', '')
if len(name) == 1:
if re.fullmatch('[0-9]', name):
name = '0' + name
else:
name = name + name
emoji = find_emoji(name, client)
if emoji is not None:
output = output.replace('{' + symbol + '}', str(emoji))
return output
示例11: get_info_for_granule
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def get_info_for_granule(self, p):
"""Return dict (re.fullmatch) for granule, based on re
Arguments:
p (pathlib.Path): path to granule
Returns:
dict: dictionary with info, such as returned by
:func:`re.fullmatch`.
"""
if not isinstance(p, pathlib.Path):
p = pathlib.Path(p)
m = self._re.fullmatch(p.name)
return m.groupdict()
示例12: from_sysfs
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def from_sysfs( cls, uio, info, parent=None ):
index = int( re.fullmatch( r'map([0-9])', info.name ).group(1) )
def getinfo( attr ):
with (info/attr).open() as f:
return f.readline().rstrip()
# If no name has been supplied, the region gets an auto-generated name
# containing the full DT path. These are useless, ignore them.
name = getinfo( 'name' )
if name == '' or name[0] == '/':
name = None
# get memory region bounds
address = int( getinfo('addr'), 0 )
size = int( getinfo('size'), 0 )
return MemRegion( parent, address, size, name, uio, index )
示例13: _is_valid_bucket
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def _is_valid_bucket(bucket_name: str):
"""Validates correctness of bucket naming.
Reference: https://cloud.google.com/storage/docs/naming
"""
if bucket_name.startswith("gs://"):
return False
if len(bucket_name) < 3 or len(bucket_name) > 63:
return False
# IP address
if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", bucket_name):
return False
if not re.fullmatch(r"([^A-Z]|-|_|[.]|)+", bucket_name):
return False
if ".." in bucket_name:
return False
if "goog" in bucket_name or "g00g" in bucket_name:
return False
return True
示例14: get
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def get(self, v, full_match=False):
""" returns a table from columns given as v
this function is equivalent to :func:`__getitem__` but preserve the
Table format and associated properties (units, description, header)
Parameters
----------
v: str
pattern to filter the keys with
full_match: bool
if set, use :func:`re.fullmatch` instead of :func:`re.match`
"""
new_keys = self.keys(v)
t = self.__class__(self[new_keys])
t.header.update(**self.header)
t._aliases.update((k, v) for (k, v) in self._aliases.items() if v in new_keys)
t._units.update((k, v) for (k, v) in self._units.items() if v in new_keys)
t._desc.update((k, v) for (k, v) in self._desc.items() if v in new_keys)
return t
示例15: is_valid_pstate_list_str
# 需要导入模块: import re [as 别名]
# 或者: from re import fullmatch [as 别名]
def is_valid_pstate_list_str(self, ps_str: str, clk_name: str) -> bool:
"""
Check if the given p-states are valid for the given clock.
:param ps_str: String of comma separated pstate numbers
:param clk_name: The target clock name
:return: True if valid
"""
if ps_str == '':
return True
if not re.fullmatch(PATTERNS['VALID_PS_STR'], ps_str):
return False
ps_list = self.prm.mclk_mask.split(',') if clk_name == 'MCLK' else self.prm.sclk_mask.split(',')
for ps_val in ps_str.split():
if ps_val not in ps_list:
return False
return True