• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python re.re_escape函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中re.re_escape函数的典型用法代码示例。如果您正苦于以下问题:Python re_escape函数的具体用法?Python re_escape怎么用?Python re_escape使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了re_escape函数的16个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __seqToRE

    def __seqToRE(self, to_convert, directive):
        """Convert a list to a regex string for matching a directive."""
        def sorter(a, b):
            """Sort based on length.

            Done in case for some strange reason that names in the locale only
            differ by a suffix and thus want the name with the suffix to match
            first.
            """
            try:
                a_length = len(a)
            except TypeError:
                a_length = 0
            try:
                b_length = len(b)
            except TypeError:
                b_length = 0
            return cmp(b_length, a_length)

        to_convert = to_convert[:]  # Don't want to change value in-place.
        for value in to_convert:
            if value != '':
                break
        else:
            return ''
        to_convert.sort(sorter)
        regex = '|'.join([re_escape(stuff) for stuff in to_convert])
        regex = '(?P<%s>%s' % (directive, regex)
        return '%s)' % regex
开发者ID:Lamouse,项目名称:Evolutionary-Creativity,代码行数:29,代码来源:_strptime.py


示例2: _punct

    def _punct(self):
        """Get the list of punction as an re escaped string.

        """
        if not hasattr(self, '_punct_initialized'):
            self._punct_initialized = re_escape(punctuation)

        return self._punct_initialized
开发者ID:zjjw,项目名称:cut_up,代码行数:8,代码来源:normalizer.py


示例3: configStrings

def configStrings(iface):
	driver = iNetwork.detectWlanModule(iface)
	ret = ""
	if driver == 'madwifi' and config.plugins.wlan.hiddenessid.value:
		ret += "\tpre-up iwconfig " + iface + " essid \"" + re_escape(config.plugins.wlan.essid.value) + "\" || true\n"
	ret += "\tpre-up wpa_supplicant -i" + iface + " -c" + getWlanConfigName(iface) + " -B -dd -D" + driver + " || true\n"
	ret += "\tpre-down wpa_cli -i" + iface + " terminate || true\n"
	return ret
开发者ID:fabiussermejio,项目名称:stbgui,代码行数:8,代码来源:plugin.py


示例4: __seqToRE

    def __seqToRE(self, to_convert, directive):
        to_convert = sorted(to_convert, key=len, reverse=True)
        for value in to_convert:
            if value != '':
                break
        else:
            return ''

        regex = '|'.join((re_escape(stuff) for stuff in to_convert))
        regex = '(?P<%s>%s' % (directive, regex)
        return '%s)' % regex
开发者ID:bizonix,项目名称:DropBoxLibrarySRC,代码行数:11,代码来源:_strptime.py


示例5: ordered_permutation_regex

def ordered_permutation_regex(sentence):
    """
    Builds a regex that matches 'ordered permutations' of a sentence's
    words.

    Args:
        sentence (str): The sentence to build a match pattern to

    Returns:
        regex (re object): Compiled regex object represented the
            possible ordered permutations of the sentence, from longest to
            shortest.
    Example:
         The sdesc_regex for an sdesc of " very tall man" will
         result in the following allowed permutations,
         regex-matched in inverse order of length (case-insensitive):
         "the very tall man", "the very tall", "very tall man",
         "very tall", "the very", "tall man", "the", "very", "tall",
         and "man".
         We also add regex to make sure it also accepts num-specifiers,
         like /2-tall.

    """
    # escape {#nnn} markers from sentence, replace with nnn
    sentence = _RE_REF.sub(r"\1", sentence)
    # escape {##nnn} markers, replace with nnn
    sentence = _RE_REF_LANG.sub(r"\1", sentence)
    # escape self-ref marker from sentence
    sentence = _RE_SELF_REF.sub(r"", sentence)

    # ordered permutation algorithm
    words = sentence.split()
    combinations = itertools.product((True, False), repeat=len(words))
    solution = []
    for combination in combinations:
        comb = []
        for iword, word in enumerate(words):
            if combination[iword]:
                comb.append(word)
            elif comb:
                break
        if comb:
            solution.append(_PREFIX + r"[0-9]*%s*%s(?=\W|$)+" % (_NUM_SEP, re_escape(" ".join(comb)).rstrip("\\")))

    # combine into a match regex, first matching the longest down to the shortest components
    regex = r"|".join(sorted(set(solution), key=lambda o: len(o), reverse=True))
    return regex
开发者ID:kod3r,项目名称:evennia,代码行数:47,代码来源:rpsystem.py


示例6: __seqToRE

    def __seqToRE(self, to_convert, directive):
        """Convert a list to a regex string for matching a directive.

        Want possible matching values to be from longest to shortest.  This
        prevents the possibility of a match occuring for a value that also
        a substring of a larger value that should have matched (e.g., 'abc'
        matching when 'abcdef' should have been the match).

        """
        to_convert = sorted(to_convert, key=len, reverse=True)
        for value in to_convert:
            if value != '':
                break
        else:
            return ''
        regex = '|'.join(re_escape(stuff) for stuff in to_convert)
        regex = '(?P<%s>%s' % (directive, regex)
        return '%s)' % regex
开发者ID:CONNJUR,项目名称:SparkyExtensions,代码行数:18,代码来源:_strptime.py


示例7: load_tests

    def load_tests(_, tests, __):  # pylint: disable=redefined-outer-name,unused-argument
        finder = DocTestFinder(exclude_empty=False)

        for root_mod in roots:
            if isinstance(root_mod, ModuleType):
                root_mod_path, root_mod_name = root_mod.__file__, root_mod.__name__
            else:
                root_mod_path, root_mod_name = root_mod

            if splitext(basename(root_mod_path))[0] == "__init__":
                root_mod_path = dirname(root_mod_path)

            if isfile(root_mod_path):
                root_mod_iter = ((dirname(root_mod_path), None, (basename(root_mod_path),)),)
            else:
                root_mod_iter = os_walk(root_mod_path)

            for dir_name, _, file_names in root_mod_iter:
                if not re_match(re_escape(root_mod_path) + _PATH_RE, dir_name):
                    continue

                mod_name = dir_name[len(root_mod_path) :].replace(ospath_sep, ".").strip(".")

                if mod_name:
                    mod_name = root_mod_name + "." + mod_name
                else:
                    mod_name = root_mod_name

                for file_name in file_names:
                    if not file_name.endswith(".py"):
                        continue

                    if file_name == "__init__.py":
                        test_mod_name = mod_name
                    else:
                        test_mod_name = mod_name + "." + splitext(file_name)[0]

                    try:
                        tests.addTest(DocTestSuite(test_mod_name, test_finder=finder))
                    except Exception as err:  # pylint: disable=broad-except
                        _LOGGER.warning("unable to load doctests from %s (%s)", test_mod_name, err, exc_info=True)

        return tests
开发者ID:pombredanne,项目名称:py-dimgx,代码行数:43,代码来源:test_doctests.py


示例8: configStrings

def configStrings(iface):
	driver = iNetwork.detectWlanModule(iface)
	ret = ""
	if driver == "brcm-wl":
		encryption = config.plugins.wlan.encryption.value
		if encryption == "WPA/WPA2":
			encryption = "WPA2"
		encryption = encryption.lower()
		if encryption == "unencrypted":
			encryption = "None"
		ret += '\tpre-up wl-config.sh -m ' + encryption + ' -k ' + config.plugins.wlan.psk.value + ' -s \"' + config.plugins.wlan.essid.value + '\" || true\n'
		ret += '\tpost-down wl-down.sh || true\n'
		return ret
	if driver == 'madwifi' and config.plugins.wlan.hiddenessid.value:
		ret += "\tpre-up iwconfig " + iface + " essid \"" + re.escape(config.plugins.wlan.essid.value) + "\" || true\n"
	ret += "\tpre-up wpa_supplicant -i" + iface + " -c" + getWlanConfigName(iface) + " -B -dd -D" + driver + " || true\n"
	if config.plugins.wlan.hiddenessid.value == True:
		ret += "\tpre-up iwconfig " + iface + " essid \"" + re_escape(config.plugins.wlan.essid.value) + "\" || true\n"
	ret += "\tpre-down wpa_cli -i" + iface + " terminate || true\n"
	return ret
开发者ID:Open-Plus,项目名称:opgui,代码行数:20,代码来源:plugin.py


示例9: configStrings

def configStrings(iface):
#--->
#-	try:
#-		device = open("/proc/stb/info/model", "r").readline().strip()
#-	except:
#-		device = ""	
#-	if device != "dm7025":
#-		rootkey = ['\x9f', '|', '\xe4', 'G', '\xc9', '\xb4', '\xf4', '#', '&', '\xce', '\xb3', '\xfe', '\xda', '\xc9', 'U', '`', '\xd8', '\x8c', 's', 'o', '\x90', '\x9b', '\\', 'b', '\xc0', '\x89', '\xd1', '\x8c', '\x9e', 'J', 'T', '\xc5', 'X', '\xa1', '\xb8', '\x13', '5', 'E', '\x02', '\xc9', '\xb2', '\xe6', 't', '\x89', '\xde', '\xcd', '\x9d', '\x11', '\xdd', '\xc7', '\xf4', '\xe4', '\xe4', '\xbc', '\xdb', '\x9c', '\xea', '}', '\xad', '\xda', 't', 'r', '\x9b', '\xdc', '\xbc', '\x18', '3', '\xe7', '\xaf', '|', '\xae', '\x0c', '\xe3', '\xb5', '\x84', '\x8d', '\r', '\x8d', '\x9d', '2', '\xd0', '\xce', '\xd5', 'q', '\t', '\x84', 'c', '\xa8', ')', '\x99', '\xdc', '<', '"', 'x', '\xe8', '\x87', '\x8f', '\x02', ';', 'S', 'm', '\xd5', '\xf0', '\xa3', '_', '\xb7', 'T', '\t', '\xde', '\xa7', '\xf1', '\xc9', '\xae', '\x8a', '\xd7', '\xd2', '\xcf', '\xb2', '.', '\x13', '\xfb', '\xac', 'j', '\xdf', '\xb1', '\x1d', ':', '?']
#-		etpm = eTPM()
#-		l2cert = etpm.getCert(eTPM.TPMD_DT_LEVEL2_CERT)
#-		if l2cert is None:
#-			return
#-		l2key = validate_certificate(l2cert, rootkey)
#-		if l2key is None:
#-			return
#-		l3cert = etpm.getCert(eTPM.TPMD_DT_LEVEL3_CERT)
#-		if l3cert is None:
#-			return
#-		l3key = validate_certificate(l3cert, l2key)
#-		if l3key is None:
#-			return
#-		rnd = get_random()
#-		if rnd is None:
#-			return
#-		val = etpm.challenge(rnd)
#-		result = decrypt_block(val, l3key)
#-	if device == "dm7025" or result[80:88] == rnd:
#---<
	if True:
		driver = iNetwork.detectWlanModule(iface)
	else:
		driver = 'dreambox'
	print 'Using "%s" as wpa-supplicant driver' % (driver)
	ret = ""
	if driver == 'madwifi' and config.plugins.wlan.hiddenessid.value:
		ret += "\tpre-up iwconfig " + iface + " essid \"" + re_escape(config.plugins.wlan.essid.value) + "\" || true\n"
	ret += "\tpre-up wpa_supplicant -i" + iface + " -c" + getWlanConfigName(iface) + " -B -dd -D" + driver + " || true\n"
	ret += "\tpre-down wpa_cli -i" + iface + " terminate || true\n"
	return ret
开发者ID:popazerty,项目名称:enigma2cuberevo,代码行数:39,代码来源:plugin.py


示例10: __init__

	def __init__(self, defaults=None, dict_type=_default_dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None,
								strict=True, empty_lines_in_values=True, default_section=DEFAULTSECT, interpolation=_UNSET, converters=_UNSET):
		# replacement of ConfigParser.__init__, do not call super-class constructor
		self._dict =      dict_type
		self._defaults =  dict_type()
		self._sections =  dict_type()
		self._proxies =    dict_type()
		self._cache =      dict()

		self._comment_prefixes =        tuple(comment_prefixes or ())
		self._inline_comment_prefixes =  tuple(inline_comment_prefixes or ())
		self._strict = strict
		self._allow_no_value = allow_no_value
		self._empty_lines_in_values = empty_lines_in_values
		self.default_section = default_section

		self._converters = ConverterMapping(self)
		if (converters is not _UNSET):
			self._converters.update(converters)

		self._proxies[default_section] = SectionProxy(self, default_section)

		if defaults:
			for key, value in defaults.items():
				self._defaults[self.optionxform(key)] = value

		self._delimiters = tuple(delimiters)
		if delimiters == ('=', ':'):
			self._optcre =                self.OPTCRE_NV if allow_no_value else self.OPTCRE
		else:
			d = "|".join(re_escape(d) for d in delimiters)
			if allow_no_value:            self._optcre = re_compile(self._OPT_NV_TMPL.format(delim=d), RE_VERBOSE)
			else:                         self._optcre = re_compile(self._OPT_TMPL.format(delim=d), RE_VERBOSE)

		if (interpolation is None):     self._interpolation = Interpolation()
		elif (interpolation is _UNSET): self._interpolation = ExtendedInterpolation()
		else:                           self._interpolation = interpolation
开发者ID:Paebbels,项目名称:PoC,代码行数:37,代码来源:__init__.py


示例11: format_to_re

def format_to_re(format):
    """Return the regular expression that matches all possible values
    the given Python 2 format string (using %(foo)s placeholders) can
    possibly resolve to.

    Each placeholder in the format string is captured in a named group.

    The difficult part here is inserting unescaped regular expression
    syntax in place of the format variables, while still properly
    escaping the rest.

    See this link for more info on the problem:
    http://stackoverflow.com/questions/2654856/python-convert-format-string-to-regular-expression
    """
    UNIQ = uuid1().hex
    assert UNIQ not in format

    class MarkPlaceholders(dict):
        def __getitem__(self, key):
            return UNIQ + ('(?P<%s>.*?)' % key) + UNIQ
    parts = (format % MarkPlaceholders()).split(UNIQ)
    for i in range(0, len(parts), 2):
        parts[i] = re_escape(parts[i])
    return ''.join(parts)
开发者ID:aishwaryaaaaaaa,项目名称:focus-android,代码行数:24,代码来源:utils.py


示例12: normalizePunctuation

    def normalizePunctuation(self, value):
        from re import compile as re_compile, escape as re_escape
        import string

        punctuations = re_compile("[%s]" % re_escape(string.punctuation))
        return punctuations.sub(" ", value)
开发者ID:uchicago-library,项目名称:uchicago-ldr-sips,代码行数:6,代码来源:LDRFileTree.py


示例13: re_escape

# ---- Imports ------------------------------------------------------------

from doctest import DocTestFinder, DocTestSuite
from logging import DEBUG, getLogger
from os import walk as os_walk
from os.path import basename, dirname, isfile, sep as ospath_sep, splitext
from re import escape as re_escape, match as re_match
from types import ModuleType
import dimgx
import tests

# ---- Constants ----------------------------------------------------------

__all__ = ("load_tests", "mkloadtests")

_PATH_RE = r"(" + re_escape(ospath_sep) + r".*)?$"

_DOCTEST_ROOTS = (dimgx, tests)

_LOGGER = getLogger(__name__)
_LOGGER.setLevel(DEBUG)

# ---- Functions ----------------------------------------------------------

# =========================================================================
def load_tests(_, tests, __):  # pylint: disable=redefined-outer-name
    """
    >>> True is not False
    True
    """
    in_len = tests.countTestCases()
开发者ID:pombredanne,项目名称:py-dimgx,代码行数:31,代码来源:test_doctests.py


示例14: search_room_by_title

	def search_room_by_title(self, keyword="", search_mode={}, req_seq=0, limit=20):
		try:
			return Mongo_Wisewolf.rooms.find({"room_title":{"$regex":"(?i).*"+re_escape(keyword)+".*"}, "room_kind":{"$ne":"support"}}).sort("_id",-1).skip(req_seq).limit(20)
		except Exception as e:
			print("Exception: MongoDao.MongoDao.Mongo_search_room_by_title:",e)
			return []
开发者ID:elwlwlwk,项目名称:wisewolf,代码行数:6,代码来源:MongoDao.py


示例15: escape_tags

def escape_tags(tags_list):
    return [ re_escape(x) for x in tags_list]
开发者ID:ekaterir,项目名称:django-tagstar,代码行数:2,代码来源:utils.py


示例16: configStrings


#.........这里部分代码省略.........
            "\xda",
            "t",
            "r",
            "\x9b",
            "\xdc",
            "\xbc",
            "\x18",
            "3",
            "\xe7",
            "\xaf",
            "|",
            "\xae",
            "\x0c",
            "\xe3",
            "\xb5",
            "\x84",
            "\x8d",
            "\r",
            "\x8d",
            "\x9d",
            "2",
            "\xd0",
            "\xce",
            "\xd5",
            "q",
            "\t",
            "\x84",
            "c",
            "\xa8",
            ")",
            "\x99",
            "\xdc",
            "<",
            '"',
            "x",
            "\xe8",
            "\x87",
            "\x8f",
            "\x02",
            ";",
            "S",
            "m",
            "\xd5",
            "\xf0",
            "\xa3",
            "_",
            "\xb7",
            "T",
            "\t",
            "\xde",
            "\xa7",
            "\xf1",
            "\xc9",
            "\xae",
            "\x8a",
            "\xd7",
            "\xd2",
            "\xcf",
            "\xb2",
            ".",
            "\x13",
            "\xfb",
            "\xac",
            "j",
            "\xdf",
            "\xb1",
            "\x1d",
            ":",
            "?",
        ]
        etpm = eTPM()
        l2cert = etpm.getCert(eTPM.TPMD_DT_LEVEL2_CERT)
        if l2cert is None:
            return
        l2key = validate_certificate(l2cert, rootkey)
        if l2key is None:
            return
        l3cert = etpm.getCert(eTPM.TPMD_DT_LEVEL3_CERT)
        if l3cert is None:
            return
        l3key = validate_certificate(l3cert, l2key)
        if l3key is None:
            return
        rnd = get_random()
        if rnd is None:
            return
        val = etpm.challenge(rnd)
        result = decrypt_block(val, l3key)
    if device == "e2pc" or result[80:88] == rnd:
        driver = iNetwork.detectWlanModule(iface)
    else:
        driver = "dreambox"
    print 'Using "%s" as wpa-supplicant driver' % (driver)
    ret = ""
    if driver != "dreambox" and config.plugins.wlan.hiddenessid.value:
        ret += "\tpre-up iwconfig " + iface + ' essid "' + re_escape(config.plugins.wlan.essid.value) + '" || true\n'
    ret += "\tpre-up wpa_supplicant -i" + iface + " -c" + getWlanConfigName(iface) + " -D" + driver + " -B\n"
    ret += "\tpost-down killall -q wpa_supplicant\n"

    return ret
开发者ID:diglam,项目名称:enigma2pc,代码行数:101,代码来源:plugin.py



注:本文中的re.re_escape函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python re.re_match函数代码示例发布时间:2022-05-26
下一篇:
Python re.re_compile函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap