我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用typing.Pattern()。
def find_latest_file(top: str, pattern: Pattern) -> str: """Find latest file matching a pattern in each directory. Find latest file defined by a file pattern and natural sort for each directory and sub directory a file pattern match occurs. Parameters ---------- top : base directory path pattern : regular expression to match file name pattern Yields ------ full file paths matching pattern. """ for root, dirs, files in os.walk(top): try: file_name = max(match_files(files, pattern), key=alphanum_key) yield os.path.join(root, file_name) except ValueError: pass
def __init__(self, wrapper: "Wrapper.Wrapper"): """ Initializes a new text processor :param wrapper: The wrapper that this text processor belongs to """ self._wrapper = wrapper self.regexes = [] # type: List[Dict[str, Pattern[str]]] self.loaded_files = [] self._logger = logging.getLogger("TextProcessor") self.server_log = logging.getLogger("MinecraftServer") self._regex_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "regex") self.load_version("generic")
def _re_fact(rex: Union[str, Regex, Pattern]) -> Regex: return rex if isinstance(rex, Regex) else Regex.cons(rex)
def _target_endpoint_pattern(path_pattern: str) -> Pattern[str]: """ Given a path pattern, return a regex which will match URLs to patch for the Target API. Args: path_pattern: A part of the url which can be matched for endpoints. For example `https://vws.vuforia.com/<this-part>`. This is compiled to be a regular expression, so it may be `/foo` or `/foo/.+` for example. """ base = 'https://vws.vuforia.com/' # type: str joined = urljoin(base=base, url=path_pattern + '$') return re.compile(joined)
def create_misuse(misuse_id: str, meta: Dict[str, Any] = None, project: Project=None, patterns: List[Pattern] = None): if not project: project = create_project("-project-") misuse = Misuse(project._base_path, project.id, misuse_id) misuse._Misuse__project = project misuse._YAML = {"location": {"file": "-dummy-/-file-", "method": "-method-()"}} misuse._PATTERNS = patterns if patterns else [] if meta: misuse._YAML.update(meta) return misuse
def check_type(value: typing.Any, hint: typing.Optional[type]) -> bool: """Check given ``value``'s type. :param value: given argument :param hint: expected type of given ``value``. as like :mod:`typing` interprets, :const:`None` is interpreted as :class:`types.NoneType` :type hint: :class:`typing.Optional`[:class:`type`] """ if hint is None: hint = NoneType actual_type = type(value) if hint is NoneType: correct = value is None elif hint is typing.Any: correct = True elif hint is typing.Pattern or hint is typing.Match: correct = isinstance(value, hint.impl_type) elif isinstance(hint, typing.TypeVar): # TODO: Check generic correct = True elif issubclass(hint, typing.Callable): actual_type, correct = check_callable(value, hint) elif issubclass(hint, typing.Tuple): actual_type, correct = check_tuple(value, hint) elif issubclass(hint, typing.Union): actual_type, correct = check_union(value, hint) else: correct = isinstance(value, hint) return actual_type, correct
def check_pattern(a: typing.Pattern) -> typing.Pattern: return a
def match_file_listing(paths, pattern: Pattern): for path in paths: filename = os.path.basename(path) if re.match(pattern, filename): yield path
def match_files(files, pattern: Pattern): """Yields file name if matches a regular expression pattern.""" for name in files: if re.match(pattern, name): yield name
def match_zipfile_members(zipfile_path: str, pattern: Pattern): """Match files to a pattern within a zip file's content.""" with ZipFile(zipfile_path, mode='r') as zfile: members = zfile.namelist() yield from match_files(members, pattern)
def find_zipfile_member(zipfile_path: str, pattern: Pattern): """Return the first match to a regex within a zip file's content.""" return next(match_zipfile_members(zipfile_path, pattern))
def replace_path(self, pattern: typing.Pattern, replacement: str) -> None: """ Replaces a given path in all fstab entries (source or destination) """ for i, line in enumerate(self._lines): if not isinstance(line, FstabLine): continue line["source"] = pattern.sub(replacement, line["source"]) line["destination"] = pattern.sub(replacement, line["destination"]) self._lines[i] = line
def __init__(self, resource=None, *args, **kwargs): # type: (Resource, *Any, **Any) -> None """ :param resource: Root resource for Twisted's standard Site implementation. Pass a resource if you want to fall back to Twisted's default resource lookup mechanism in case no route matches. If None is passed, defaults to a NoResource() instance. """ resource = resource or NoResource() Site.__init__(self, resource, *args, **kwargs) self.routes = {} # type: Dict[Pattern, Resource]
def cons(pattern: Union[str, Pattern]) -> 'Regex': spec = pattern.pattern if isinstance(pattern, Pattern) else pattern rex = pattern if isinstance(pattern, Pattern) else re.compile(pattern) return Regex(spec, rex)
def __init__(self, spec: str, rex: Union[None, Pattern]=None) -> None: self.spec = spec self.rex = re.compile(spec) if rex is None else rex