本文整理匯總了Python中re.Pattern方法的典型用法代碼示例。如果您正苦於以下問題:Python re.Pattern方法的具體用法?Python re.Pattern怎麽用?Python re.Pattern使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類re
的用法示例。
在下文中一共展示了re.Pattern方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: StepCommandRE
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def StepCommandRE(check, step_odict, step, expected_patterns):
"""Assert that a step's command matches a given list of regular expressions.
Args:
step (str) - The step to check the command of.
expected_patterns (list(str, re.Pattern)) - Regular expressions to match the
elements of the step's command. The i-th element of the step's command
will be matched against the i-th regular expression. If the pattern does
not match the entire argument string, it is a CHECK failure.
Usage:
yield (
TEST
+ api.post_process(StepCommandRE, 'step-name',
['my', 'command', '.*'])
)
"""
cmd = step_odict[step].cmd
for expected, actual in zip(expected_patterns, cmd):
check(_fullmatch(expected, actual))
unmatched = cmd[len(expected_patterns):]
check('all arguments matched', not unmatched)
unused = expected_patterns[len(cmd):]
check('all patterns used', not unused)
示例2: compile_regex
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def compile_regex(item):
r""" Compile a clause into a regex. Clause checking in AWS is case insensitive
The following regex symbols will be replaced to make AWS * and ? matching a regex
* -> .* (wildcard)
? -> .? (single character wildcard)
. -> \\. (make period a literal period)
Arguments:
item {str} -- the item to create the regex for
Returns:
[re.Pattern] -- The precompiled regex pattern.
If the pattern does not compile it will return an re.Pattern of empty string
"""
if isinstance(item, str):
item = item.replace(".", "\\.").replace("*", ".*").replace("?", ".?")
try:
item = re.compile(item, flags=re.IGNORECASE)
except re.error:
logger.warning(f"Regex did not compile for {item}")
# in this case it must still return a regex.
# So it will return an re.Pattern of empry stringm
item = re.compile("", flags=re.IGNORECASE)
return item
示例3: assertWarnsRegex
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def assertWarnsRegex(self, expected_warning, expected_regex,
*args, **kwargs):
"""Asserts that the message in a triggered warning matches a regexp.
Basic functioning is similar to assertWarns() with the addition
that only warnings whose messages also match the regular expression
are considered successful matches.
Args:
expected_warning: Warning class expected to be triggered.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertWarnsRegex is used as a context manager.
"""
context = _AssertWarnsContext(expected_warning, self, expected_regex)
return context.handle('assertWarnsRegex', args, kwargs)
示例4: __init__
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def __init__(self, path, filename_pattern=None):
if isinstance(filename_pattern, re.Pattern): # pylint: disable=no-member
filename_re = filename_pattern
else:
filename_re = re.compile(filename_pattern)
basename = os.path.basename(path)
match = filename_re.match(basename)
if match is None:
raise ValueError('filename {} does not match required pattern')
tract, patch_x, patch_y, index = match.groups()
self.path = path
self.tract = int(tract)
self.patch = '{},{}'.format(patch_x, patch_y)
self.index = int(index)
self._handle = None
self._keys = None
self._len = None
示例5: __init__
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def __init__(self, path, filename_pattern=None):
if isinstance(filename_pattern, re.Pattern): # pylint: disable=no-member
filename_re = filename_pattern
else:
filename_re = re.compile(filename_pattern)
basename = os.path.basename(path)
match = filename_re.match(basename)
if match is None:
raise ValueError('filename {} does not match required pattern')
z_block_lower, pixelid = tuple(map(int, match.groups()))
self.z_block_lower = int(z_block_lower)
self.healpix_pixel = int(pixelid)
self.path = path
self._handle = None
self._keys = None
self._len = None
示例6: on
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def on(self, pattern, fn):
"""Register a function to trigger on a certain pattern.
The pattern can be an event name or a glob.
* `**` in a pattern matches any character sequence including
the / delimiter
* `/**/` can also match `/`
* `*` matches any character sequence except /
* A pattern that does not start with `/` is equivalent to the same
pattern prepended with `/**/`, e.g. `apple` is equivalent to
`/**/apple`
"""
if not isinstance(pattern, re.Pattern):
pattern = glob_to_regex(pattern)
self.listeners.append((pattern, fn))
示例7: findLabel
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def findLabel(self, query, create=False):
"""Find a label with the given name.
Args:
name (Union[_sre.SRE_Pattern, str]): A str or regular expression to match against the name.
create (bool): Whether to create the label if it doesn't exist (only if name is a str).
Returns:
Union[gkeepapi.node.Label, None]: The label.
"""
is_str = isinstance(query, six.string_types)
name = None
if is_str:
name = query
query = query.lower()
for label in self._labels.values():
# Match the label against query, which may be a str or Pattern.
if (is_str and query == label.name.lower()) or \
(isinstance(query, Pattern) and query.search(label.name)):
return label
return self.createLabel(name) if create and is_str else None
示例8: __init__
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def __init__(self, s: asyncio.streams.StreamWriter, sl_client: Union[slack.Slack], nouserlist: bool, autojoin: bool, provider: Provider):
self.nick = b''
self.username = b''
self.realname = b''
self.parted_channels: Set[bytes] = set()
self.hostname = gethostname().encode('utf8')
self.provider = provider
self.s = s
self.sl_client = sl_client
self.nouserlist = nouserlist
self.autojoin = autojoin
self._usersent = False # Used to hold all events until the IRC client sends the initial USER message
self._held_events: List[slack.SlackEvent] = []
self._magic_users_id = 0
self._magic_regex: Optional[re.Pattern] = None
if self.provider == Provider.SLACK:
self.substitutions = _SLACK_SUBSTITUTIONS
else:
self.substitutions = []
示例9: _parse_filename
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def _parse_filename(filename, delimiter, regex):
"""Parse the input filename and return a list of metadata.
Args:
filename: Filename to parse metadata from
delimiter: Delimiter character to split the filename on
regex: Compiled regular expression pattern to process file with
:param filename: str
:param delimiter: str
:param regex: re.Pattern
:return metadata: list
"""
# Split the filename on delimiter if it is a single character
if len(delimiter) == 1:
metadata = filename.split(delimiter)
else:
metadata = re.search(regex, filename)
if metadata is not None:
metadata = list(metadata.groups())
else:
metadata = []
return metadata
###########################################
示例10: do_include_filepath
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def do_include_filepath(filepath: str, exclude_re: Optional["re.Pattern"]) -> bool:
"""Determine whether `filepath` should be included in docstring search
Parameters
----------
filepath: String
Filepath to match with `exclude_re`. If extension is not ".py", it will be excluded
exclude_re: re.Pattern, or None
Pattern for files to be excluded. If None, `exclude_re` is ignored
Returns
-------
Boolean
True if `filepath` should be searched, else False"""
if not filepath.endswith(".py"):
return False
if exclude_re is not None:
return not exclude_re.match(filepath)
return True
示例11: _js_select_by
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def _js_select_by(self, term, number):
if isinstance(term, Pattern):
js_rx = term.pattern
js_rx = js_rx.replace('\\A', '^', 1)
js_rx = js_rx.replace('\\Z', '$', 1)
js_rx = js_rx.replace('\\z', '$', 1)
js_rx = re.sub(r'\(\?#.+\)', '', js_rx)
js_rx = re.sub(r'\(\?-\w+:', '(', js_rx)
elif type(term) in [six.text_type, six.binary_type]:
js_rx = '^{}$'.format(term)
else:
raise TypeError('expected String or Regexp, got {}'.format(term))
for way in ['text', 'label', 'value']:
self._element_call(lambda: self._execute_js('selectOptions{}'.format(way.capitalize()),
self, js_rx, str(number)))
if self._is_matching_option(way, term):
return self.selected_options[0].text
self._raise_no_value_found(term)
示例12: _label_element_string
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def _label_element_string(self):
label = self.selector.pop('label_element', None)
if label is None:
return ''
key = 'contains_text' if isinstance(label, Pattern) else 'text'
value = self._process_attribute(key, label)
if 'contains_text' in self.built:
self.built['label_element'] = self.built.pop('contains_text')
# TODO: This conditional can be removed when we remove this deprecation
if isinstance(label, Pattern):
self.built['label_element'] = label
return ''
else:
return "[@id=//label[{0}]/@for or parent::label[{0}]]".format(value)
示例13: _match_attributes
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def _match_attributes(self, obj, until=True):
from ..elements.element import Element
def check(key):
expected = obj.get(key)
if isinstance(self, Element) and not hasattr(self, key):
actual = self.get_attribute(key)
else:
attr = getattr(self, key)
actual = attr() if callable(attr) else attr
if isinstance(expected, Pattern):
return re.search(expected, actual) is not None
else:
return expected == actual
def func(*args):
truthy = all if until else any
return truthy(check(key) for key in obj)
return func
示例14: _xpath_adjacent
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def _xpath_adjacent(self, **kwargs):
from .elements.html_elements import HTMLElement, HTMLElementCollection
import nerodia
plural = kwargs.pop('plural', None)
index = kwargs.pop('index', None)
tag_name = kwargs.get('tag_name')
if not (plural or any(isinstance(val, Pattern) for val in kwargs.values())):
kwargs['index'] = index or 0
if not plural and tag_name:
klass = nerodia.element_class_for(tag_name)
elif not plural:
klass = HTMLElement
elif tag_name:
klass = nerodia.element_class_for('{}_collection'.format(tag_name),
HTMLElementCollection)
else:
klass = HTMLElementCollection
return klass(self, kwargs)
示例15: grep_param_names
# 需要導入模塊: import re [as 別名]
# 或者: from re import Pattern [as 別名]
def grep_param_names(self, regexp):
"""
create a list of parameters, matching regular expression regexp
"""
if not isinstance(regexp, _pattern_type): regexp = compile(regexp)
found_params = []
def visit(innerself, regexp):
if (innerself is not self) and regexp.match(innerself.hierarchy_name().partition('.')[2]):
found_params.append(innerself)
self.traverse(visit, regexp)
return found_params