当前位置: 首页>>代码示例>>Python>>正文


Python re.compile方法代码示例

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


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

示例1: interpolate_url

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def interpolate_url(self):
        pattern = r'\{([a-z_]+)\}'
        regex = re.compile(pattern)
        start = 0
        new_url = self.resource_url

        while (start + 1) < len(self.resource_url):
            match = regex.search(self.resource_url, start)
            if match is None:
                return new_url

            param = match.group(1)
            val = getattr(self, param, None)
            if val is None:
                raise ValueError("Missing variable value")
            new_url = new_url.replace('{' + param + '}', str(val))
            start = match.end(1) + 1

        return new_url 
开发者ID:airshipit,项目名称:drydock,代码行数:21,代码来源:base.py

示例2: test_invalid_storage_partitioning

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def test_invalid_storage_partitioning(self, deckhand_ingester,
                                          drydock_state, input_files,
                                          mock_get_build_data):
        input_file = input_files.join("invalid_validation.yaml")

        design_ref = "file://%s" % str(input_file)

        orch = Orchestrator(
            state_manager=drydock_state, ingester=deckhand_ingester)

        status, site_design = Orchestrator.get_effective_site(orch, design_ref)

        validator = StoragePartitioning()
        message_list = validator.execute(site_design)

        regex = re.compile('Volume group .+ not assigned any physical volumes')

        for msg in message_list:
            msg = msg.to_dict()
            LOG.debug(msg)
            assert len(msg.get('documents')) > 0
            assert msg.get('error')
            assert regex.search(msg.get('message')) is not None

        assert len(message_list) == 2 
开发者ID:airshipit,项目名称:drydock,代码行数:27,代码来源:test_validation_rule_storage_partitioning.py

示例3: test_invalid_no_duplicate_IPs

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def test_invalid_no_duplicate_IPs(self, input_files, drydock_state,
                                      deckhand_ingester):
        input_file = input_files.join("invalid_validation.yaml")
        design_ref = "file://%s" % str(input_file)

        orch = Orchestrator(
            state_manager=drydock_state, ingester=deckhand_ingester)

        status, site_design = Orchestrator.get_effective_site(orch, design_ref)

        validator = NoDuplicateIpsCheck()
        message_list = validator.execute(site_design)

        regex = re.compile('Duplicate IP Address Found: [0-9.]+')

        for msg in message_list:
            msg = msg.to_dict()
            LOG.debug(msg)
            assert len(msg.get('documents')) > 0
            assert msg.get('error') is True
            assert regex.search(msg.get('message')) is not None 
开发者ID:airshipit,项目名称:drydock,代码行数:23,代码来源:test_validation_rule_no_duplicate_IPs.py

示例4: test_invalid_partition_mountpoints

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def test_invalid_partition_mountpoints(self, deckhand_ingester,
                                           drydock_state, input_files,
                                           mock_get_build_data):

        input_file = input_files.join("invalid_validation.yaml")
        design_ref = "file://%s" % str(input_file)

        orch = Orchestrator(
            state_manager=drydock_state, ingester=deckhand_ingester)

        status, site_design = Orchestrator.get_effective_site(orch, design_ref)

        validator = StorageMountpoints()
        message_list = validator.execute(site_design, orchestrator=orch)

        regex = re.compile('Mountpoint .+ already exists')

        for msg in message_list:
            msg = msg.to_dict()
            LOG.debug(msg)
            assert regex.search(msg.get('message')) is not None
            assert msg.get('error') is True 
开发者ID:airshipit,项目名称:drydock,代码行数:24,代码来源:test_validation_rule_storage_mountpoint.py

示例5: test_invalid_vg_mountpoints

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def test_invalid_vg_mountpoints(self, deckhand_ingester, drydock_state,
                                    input_files, mock_get_build_data):

        input_file = input_files.join("invalid_mountpoint.yaml")
        design_ref = "file://%s" % str(input_file)

        orch = Orchestrator(
            state_manager=drydock_state, ingester=deckhand_ingester)

        status, site_design = Orchestrator.get_effective_site(orch, design_ref)

        validator = StorageMountpoints()
        message_list = validator.execute(site_design, orchestrator=orch)

        regex = re.compile('Mountpoint .+ already exists')

        for msg in message_list:
            msg = msg.to_dict()
            LOG.debug(msg)
            assert regex.search(msg.get('message')) is not None
            assert msg.get('error') is True 
开发者ID:airshipit,项目名称:drydock,代码行数:23,代码来源:test_validation_rule_storage_mountpoint.py

示例6: test_invalid_boot_storage_small

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def test_invalid_boot_storage_small(self, deckhand_ingester, drydock_state,
                                        input_files, mock_get_build_data):
        input_file = input_files.join("invalid_boot_storage_small.yaml")
        design_ref = "file://%s" % str(input_file)

        orch = Orchestrator(
            state_manager=drydock_state, ingester=deckhand_ingester)

        status, site_design = Orchestrator.get_effective_site(orch, design_ref)

        validator = BootStorageRational()
        message_list = validator.execute(site_design, orchestrator=orch)

        regex = re.compile('.+ volume must be > .+GB')

        for msg in message_list:
            msg = msg.to_dict()
            LOG.debug(msg)
            assert len(msg.get('documents')) > 0
            assert regex.search(msg.get('message')) is not None
            assert msg.get('error')

        assert len(message_list) == 4 
开发者ID:airshipit,项目名称:drydock,代码行数:25,代码来源:test_validation_rule_boot_storage.py

示例7: test_invalid_network_cidr

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def test_invalid_network_cidr(self, mocker, deckhand_ingester,
                                  drydock_state, input_files):

        input_file = input_files.join("invalid_network_cidr.yaml")
        design_ref = "file://%s" % str(input_file)

        orch = Orchestrator(
            state_manager=drydock_state, ingester=deckhand_ingester)

        status, site_design = Orchestrator.get_effective_site(orch, design_ref)

        validator = CidrValidity()
        message_list = validator.execute(site_design, orchestrator=orch)
        msg = message_list[0].to_dict()

        regex_diagnostic = re.compile('Provide a CIDR acceptable by MAAS: .+')
        regex_message = re.compile('The provided CIDR .+ has host bits set')

        assert len(message_list) >= 1
        assert msg.get('error') is True
        assert any([
            regex_diagnostic.search(msg.get('diagnostic')),
            regex_message.search(msg.get('message'))
                  ]) 
开发者ID:airshipit,项目名称:drydock,代码行数:26,代码来源:test_validation_rule_network_cidr.py

示例8: convert_param

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def convert_param(method, param):
    # remove notation, split by upper, convert to lowercase
    param_sanitized = param.replace('*', '')
    substr = param_sanitized
    try:
        substr = re.search('([A-Z]\w+)', param_sanitized).group(1)
    except:
        pass
    case_re = re.compile(r'((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
    converted_param = case_re.sub(r'_\1', substr).lower()
    if converted_param in keyword.kwlist or converted_param in dir(__builtins__):
        converted_param += '_param'
    # check for duplicates. if seen, append number to end
    if 'params' in method and len([param for param in method['params'] if param['name'] == converted_param]):
        param_names = [param['name'] for param in method['params']]
        for x in range(2, 10):
            count_name = '{:s}{:d}'.format(converted_param, x)
            if count_name not in param_names:
                converted_param = count_name
                break
    return converted_param 
开发者ID:fireeye,项目名称:cWMI,代码行数:23,代码来源:i_to_m.py

示例9: _parse_summary

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def _parse_summary(self):
        """Grab signature (if given) and summary"""
        summary = self._doc.read_to_next_empty_line()
        summary_str = "\n".join([s.strip() for s in summary])
        if re.compile('^([\\w. ]+=)?[\\w\\.]+\\(.*\\)$').match(summary_str):
            self['Signature'] = summary_str
            if not self._is_at_section():
                self['Summary'] = self._doc.read_to_next_empty_line()
        elif re.compile('^[\\w]+\n[-]+').match(summary_str):
            self['Summary'] = ''
            self._doc.reset()
        else:
            self['Summary'] = summary

        if not self._is_at_section():
            self['Extended Summary'] = self._read_to_next_section() 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:18,代码来源:docscrape.py

示例10: format_pixiv_illust_original_url

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def format_pixiv_illust_original_url(id_url, mode=1):
    tag = 'Format_Pixiv_Illust_Original_Url'
    if mode == 1:
        contents = get_text_from_url(id_url)
        try:
            img_src_re = re.compile(r'\"urls\":{.*?}')
            img_src = img_src_re.findall(contents)
            final_dict = json.loads("{" + img_src[0] + "}")
            return final_dict['urls']['original']
        except Exception as e:
            print_with_tag(tag, "An error occurred when parsing the json file.")
            print_with_tag(tag, e)
    elif mode == 2:
        data_list = []
        json_datas = get_text_from_url(id_url)
        json_datas_format = json.loads(json_datas)['body']
        for urls in json_datas_format:
            data_list.append(urls['urls']['original'])
        return data_list 
开发者ID:SuzukiHonoka,项目名称:Starx_Pixiv_Collector,代码行数:21,代码来源:start.py

示例11: tweak

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def tweak(self, content):
        tweaked = self.legacy_tweak(content)
        if tweaked:
            return tweaked
        apply_persistence_to_all_lines = \
            0 < self.setup_params.persistence_size and \
            not self.config_is_persistence_aware(content)
        matching_re = r'^(\s*(%s)\s*)(.*)$' % self.BOOT_PARAMS_STARTER
        kernel_parameter_line_pattern = re.compile(
            matching_re,
            flags = re.I | re.MULTILINE)
        out = self.tweak_first_match(
            content,
            kernel_parameter_line_pattern,
            apply_persistence_to_all_lines,
            self.param_operations(),
            self.param_operations_for_persistence())
        
        return self.post_process(out) 
开发者ID:mbusb,项目名称:multibootusb,代码行数:21,代码来源:update_cfg_file.py

示例12: _match_major_minor

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def _match_major_minor(cls, value):
        """
        Match the number under the assumption that it is a major,minor pair.

        :param str value: value to match
        :returns: the device number or None
        :rtype: int or NoneType
        """
        major_minor_re = re.compile(
           r'^(?P<major>\d+)(\D+)(?P<minor>\d+)$'
        )
        match = major_minor_re.match(value)
        return match and os.makedev(
           int(match.group('major')),
           int(match.group('minor'))
        ) 
开发者ID:mbusb,项目名称:multibootusb,代码行数:18,代码来源:discover.py

示例13: escape_wikitext

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def escape_wikitext(wikitext):
    """Escape wikitext for use in file description."""
    rep = OrderedDict([
        ('{|', '{{(}}&#124;'),
        ('|}', '&#124;{{)}}'),
        ('||', '&#124;&#124;'),
        ('|', '&#124;'),
        ('[[', '{{!((}}'),
        (']]', '{{))!}}'),
        ('{{', '{{((}}'),
        ('}}', '{{))}}'),
        ('{', '{{(}}'),
        ('}', '{{)}}'),
    ])
    rep = dict((re.escape(k), v) for k, v in rep.iteritems())
    pattern = re.compile("|".join(rep.keys()))
    return pattern.sub(lambda m: rep[re.escape(m.group(0))], wikitext)


# Source: mediawiki.Title.js@9df363d 
开发者ID:toolforge,项目名称:video2commons,代码行数:22,代码来源:urlextract.py

示例14: __init__

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def __init__(self, interval, stat_func=None, pattern='.*', sort=False):
        if stat_func is None:
            def asum_stat(x):
                """returns |x|/size(x), async execution."""
                return ndarray.norm(x)/sqrt(x.size)
            stat_func = asum_stat
        self.stat_func = stat_func
        self.interval = interval
        self.activated = False
        self.queue = []
        self.step = 0
        self.exes = []
        self.re_prog = re.compile(pattern)
        self.sort = sort
        def stat_helper(name, array):
            """wrapper for executor callback"""
            array = ctypes.cast(array, NDArrayHandle)
            array = NDArray(array, writable=False)
            if not self.activated or not self.re_prog.match(py_str(name)):
                return
            self.queue.append((self.step, py_str(name), self.stat_func(array)))
        self.stat_helper = stat_helper 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:24,代码来源:monitor.py

示例15: _collect_params_with_prefix

# 需要导入模块: import re [as 别名]
# 或者: from re import compile [as 别名]
def _collect_params_with_prefix(self, prefix=''):
        if prefix:
            prefix += '.'
        pattern = re.compile(r'(l|r)(\d)_(i2h|h2h)_(weight|bias)\Z')
        def convert_key(m, bidirectional): # for compatibility with old parameter format
            d, l, g, t = [m.group(i) for i in range(1, 5)]
            if bidirectional:
                return '_unfused.{}.{}_cell.{}_{}'.format(l, d, g, t)
            else:
                return '_unfused.{}.{}_{}'.format(l, g, t)
        bidirectional = any(pattern.match(k).group(1) == 'r' for k in self._reg_params)

        ret = {prefix + convert_key(pattern.match(key), bidirectional) : val
               for key, val in self._reg_params.items()}
        for name, child in self._children.items():
            ret.update(child._collect_params_with_prefix(prefix + name))
        return ret 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:19,代码来源:rnn_layer.py


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