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


Python re.re_match函数代码示例

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


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

示例1: _compareAttribute

 def _compareAttribute(self, node1, node2, attr):
     attr1 = node1.getAttribute(attr)
     attr2 = node2.getAttribute(attr)
     if attr2.startswith("regexp:"):
         return bool(re_match(attr2[7:], attr1))
     elif attr2.startswith("glob:"):
         return bool(re_match(glob_trans(attr2[5:]), attr1))
     else:
         return attr1 == attr2
开发者ID:eeejay,项目名称:specular,代码行数:9,代码来源:specular_serial.py

示例2: route_for_task

 def route_for_task(self, task, args=None, kwargs=None):
     parts = task.split('.')
     if re_match(r'^mp[a-z_]+\.sync\.[a-z_]+$', task) is not None:
         return {
             'routing_key': task,
             'queue': parts[0] + '.sync',
             }
     elif re_match(r'^mp[a-z_]+\.async\.[a-z_]+$', task) is not None:
         return {
             'routing_key': task,
             'queue': parts[0] + '.async',
             }
     return None
开发者ID:sethc23,项目名称:shared_scripts,代码行数:13,代码来源:app_factory.py

示例3: create_user

    def create_user(self, first, last, gender="M", username=None, password=None, role="Provider"):
        url = self.base + USER_FORM_URL

        if not first:
            raise CreateUserException("Given name can't be blank")
        first_names = first.split()

        if not last:
            raise CreateUserException("Family name can't be blank")

        if not username:
            username = "".join([c[0] for c in first_names] + [last]).lower()

        if not password:
            password = []
            for i in range(0, 3):
                password += [random.choice(string.digits), random.choice(string.lowercase)]
            random.shuffle(password)
            password = "".join(password)
        else:
            if (
                len(password) < 6
                or not (re_match("\d", password) and re_match("[a-zA-Z]", password))
                or re_match("\s", password)
            ):
                raise CreateUserException(
                    "Password must be at least six " "characters and contain at least " "one letter and number"
                )

        params = {}
        if len(first_names) > 1:
            params.update({"names[0].middleName": first_names.pop().title()})

        params.update(
            {
                "names[0].givenName": " ".join(first_names).title(),
                "names[0].familyName": last.title(),
                "gender": gender,
                "username": username.lower(),
                "userFormPassword": password,
                "confirm": password,
                "roleStrings": role,
            }
        )

        data = urlencode(params)
        response = self.opener.open(url, data).read()
        if response.find("Username or System Id taken") != -1:
            raise CreateUserException("Username taken")
开发者ID:katembu,项目名称:rapidsms-impl,代码行数:49,代码来源:omrs_users.py

示例4: versions_from_file

def versions_from_file(filename):
   versions = {}
   try:
      with open(filename) as f:
         for line in f.readlines():
            mo = re_match("version_version = '([^']+)'", line)
            if mo:
               versions['version'] = mo.group(1)
            mo = re_match("version_full = '([^']+)'", line)
            if mo:
               versions['full'] = mo.group(1)
   except EnvironmentError:
      return {}

   return versions
开发者ID:peter1000,项目名称:JqPyCharts,代码行数:15,代码来源:versioneer.py

示例5: __init__

    def __init__( self, data, b0_thr = 0 ) :
        """Initialize the acquisition scheme.

        Parameters
        ----------
        data : string or numpy.ndarray
            The filename of the scheme or a matrix containing the actual values
        b0_thr : float
            The threshold on the b-values to identify the b0 images (default: 0)
        """
        if type(data) is str :
            # try loading from file
            try :
                n = 0 # headers lines to skip to get to the numeric data
                with open(data) as fid :
                    for line in fid :
                        if re_match( r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?', line.strip() ) :
                            break
                        n += 1
                tmp = np.loadtxt( data, skiprows=n )
            except :
                raise IOError( 'Unable to open scheme file' )
            self.load_from_table( tmp, b0_thr )
        else :
            # try loading from matrix
            self.load_from_table( data, b0_thr )
开发者ID:davidrs06,项目名称:AMICO,代码行数:26,代码来源:scheme.py

示例6: get_platform

def get_platform():

    from os.path import exists
    from re import match as re_match

    platforms = []
    arch = run_output('uname', '-m').replace('686', '386')
    platforms.append(arch)

    if exists('/etc/debian_version'):
        platforms.append('debian')

    if exists('/etc/redhat-release'):
        platforms.append('redhat')

        version = file('/etc/redhat-release').read().strip()
        badge = 'Red Hat Enterprise Linux Server release (\d+)\.(\d+)'
        match = re_match(badge, version)
        if match:
            platforms.append('rhel%s' % match.group(1))

    if exists('/etc/arch-release'):
        platforms.append('archlinux')

    verbose('PLATFORMS: %s' % ",".join(platforms))
    return platforms
开发者ID:jianingy,项目名称:campcraft,代码行数:26,代码来源:campcraft.py

示例7: _glob_match

 def _glob_match(self, pattern, string):
     """
     Match given string, by escaping regex characters
     """
     # regex flags Multi-line, Unicode, Locale
     return bool(re_match(glob_trans(pattern), string,
                          re.M | re.U | re.L))
开发者ID:colinligertwood,项目名称:ldtp2,代码行数:7,代码来源:utils.py

示例8: _stem_with_duplicate_character_check

 def _stem_with_duplicate_character_check(word, del_len):
     if word[-1] == 's':
         del_len += 1
     stemmed_word = word[:-del_len]
     if re_match(r'.*(\w)\1$', stemmed_word):
         stemmed_word = stemmed_word[:-1]
     return stemmed_word
开发者ID:chrislit,项目名称:abydos,代码行数:7,代码来源:_uea_lite.py

示例9: parse_option

def parse_option(args, spec, options={}, header='', footer=''):
    from re import match as re_match
    from getopt import getopt, GetoptError
    help_message = header
    short_opt, long_opt, opt_cond = '', [], {}
    for line in spec.splitlines():
        match = re_match('([a-z])\|(\w+)([:=])(.+)', line)
        if not match:
            continue
        opt_s, opt_l, opt_v, opt_h = match.groups()
        help_message = (help_message +
                        '\n-%s, --%s\t\t%s' % (opt_s, opt_l, opt_h))
        opt_cond['-' + opt_s] = opt_l
        opt_cond['--' + opt_l] = opt_l
        if opt_v == '=':
            opt_s = opt_s + ':'
            opt_l = opt_l + '='
        short_opt = short_opt + opt_s
        long_opt.append(opt_l)

    help_message = help_message + '\n' + footer
    try:
        opts, args = getopt(args, short_opt, long_opt)
        for optname, optval in opts:
            if optname in opt_cond:
                options[opt_cond[optname]] = optval
        return options
    except GetoptError as err:
        from sys import stderr, exit
        print >>stderr, 'ERROR:', str(err)
        print >>stderr, '\n', help_message, '\n'
        exit(1)
开发者ID:jianingy,项目名称:campcraft,代码行数:32,代码来源:campcraft.py

示例10: do_get_blog_tag_posts

def do_get_blog_tag_posts(parser, token):
    """
    Get the blog Posts for a specified tag and store it in a context variable.
    
    Usage::

      {% get_blog_tag_posts [tag_name] as [varname] %}
    
    tag should be a variable or a quoted string

    Example::
    
      {% get_blog_tag_posts "django" as blog_posts %}
    
    """
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError(
            '%r tag requires arguments' % token.contents.split()[0])
    m = re_match(r'(.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError(
            '%r tag had invalid arguments' % tag_name)
    tag, var_name = m.groups()
    return BlogTagPostsNode(tag, var_name)
开发者ID:davisd,项目名称:django-blogyall,代码行数:26,代码来源:blog_tags.py

示例11: o_b58

def o_b58(r160, magicbyte=0):
    """ Base58 encoding w leading zero compact
    """
    from re import match as re_match
    inp_fmtd = chr(int(magicbyte)) + r160
    leadingzbytes = len(re_match('^\x00*', inp_fmtd).group(0))
    checksum = hashlib.sha256(hashlib.sha256(inp_fmtd).digest()).digest()[:4]
    return '1' * leadingzbytes + encode(decode(inp_fmtd + checksum, 256), 58, 0)
开发者ID:techknowio,项目名称:makelabel,代码行数:8,代码来源:paperwal.py

示例12: base58Encode

def base58Encode(r160, magicbyte=0, prefix=1, length=0):
	""" Base58 encoding w leading zero compact
	"""
	from re import match as re_match
	inp_fmtd = chr(int(magicbyte if magicbyte < 255 else 255)) + r160
	leadingzbytes = len(re_match('^\x00*', inp_fmtd).group(0))
	checksum = hashlib.sha256(hashlib.sha256(inp_fmtd).digest()).digest()[:4]
	return str(prefix) * leadingzbytes + enc.encode(enc.decode(inp_fmtd + checksum, 256), 58, 0)
开发者ID:eskimowallet,项目名称:eskimo,代码行数:8,代码来源:address.py

示例13: match_regexp

def match_regexp(transition, event, _token, _fsa):
    """
    The 'regexp' matcher.

    With this matcher,
    transition conditions are interpreted as regular expressions.
    Note that the *whole* event must match the regular expression
    (this is ensured by automatically prepending ``^`` and appending ``$`` to the condition).
    """
    return re_match('^%s$' % transition['condition'], event)
开发者ID:pchampin,项目名称:fsa4streams,代码行数:10,代码来源:matcher.py

示例14: normalise_email

 def normalise_email(self):
     """
     Normalise the email address provides into an account URL
     """
     url = urlparse(self.request_email, "acct")
     if url.scheme != "acct":
         raise TypeError()
     self.request_email = url
     match = re_match(".*\@(.*)", url.path)
     self.hostmeta = HostMeta(match.group(1))
开发者ID:Zauberstuhl,项目名称:pyaspora,代码行数:10,代码来源:protocol.py

示例15: strip_url

    def strip_url(url):
        split_results = urlsplit(url)
        path = split_results.path

        path_match = re_match("/(sales|lettings)/(.*?)/(\d*)/?", path)
        category, tag, prop_id = path_match.groups() \
                if path_match \
                else ("", "", "")

        return category, tag, prop_id
开发者ID:nicr9,项目名称:daftpunk,代码行数:10,代码来源:worker.py


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