コード例 #1
0
def re_search(regex: typing.Union[typing.Pattern[str], str],
              text: typing.AnyStr,
              dotall: bool = True,
              default: str = "") -> str:
    """
    抽取正则规则的第一组元素

    :param regex: 正则对象或字符串
    :param text: 被查找的字符串
    :param dotall: 正则.是否匹配所有字符
    :param default: 找不到时的默认值
    :return: 抽取正则规则的第一组
    """
    if isinstance(text, bytes):
        text = text.decode("utf-8")
    if not isinstance(regex, list):
        regex = [regex]
    for rex in regex:
        rex = (re.compile(rex, re.DOTALL)
               if dotall else re.compile(rex)) if isinstance(rex, str) else rex
        match_obj = rex.search(text)
        if match_obj is not None:
            t = match_obj.group(1).replace('\n', '')
            return t
    return default
コード例 #2
0
ファイル: core.py プロジェクト: sirosen/webargs
def parse_json(s: typing.AnyStr, *, encoding: str = "utf-8") -> typing.Any:
    if isinstance(s, str):
        decoded = s
    else:
        try:
            decoded = s.decode(encoding)
        except UnicodeDecodeError as exc:
            raise json.JSONDecodeError(
                f"Bytes decoding error : {exc.reason}",
                doc=str(exc.object),
                pos=exc.start,
            )
    return json.loads(decoded)