zoukankan      html  css  js  c++  java
  • re.sub函数的深入了解

    看到一道题目,只用re.sub(),不得其解。

    把下划线命名(也叫蛇形命名,所有单词都是小写,中间通过下划线连接),转化为小驼峰命名法(第一个单词小写,其余所有单词首字母大写)。
    例如'go_to_next_page',转化后改写为'goToNextPage'

    请使用正则表达式替换方法,即re.sub()。

    参考文章: https://www.jianshu.com/p/f41dcef2bd1b

    re.sub函数

    re.sub函数是Python内置的re模块的一个字符串替换函数,支持正则替换。函数文档如下:

    help(re.sub)
    Help on function sub in module re:
    sub(pattern, repl, string, count=0, flags=0)
        Return the string obtained by replacing the leftmost
        non-overlapping occurrences of the pattern in string by the
        replacement repl.  repl can be either a string or a callable;
        if a string, backslash escapes in it are processed.  If it is
        a callable, it's passed the match object and must return
        a replacement string to be used.
    • pattern:是一个正则表达式,匹配要替换的子串。

    • repl:可以是一个字符串,支持对pattern中分组的后向引用。

    • string:要进行替换操作的字符串。

    • count:要替换掉多少个子串(按从左到右的顺序),默认值为0,表示替换能被pattern匹配到的所有子串。

    • flags:正则内置属性,默认值为0,表示不使用任何内置属性。

    根据文档,repl也可以是一个callable对象(函数),这个函数的入参为pattern正则匹配到的对象,返回值为一个字符串,表示要替换成的字符串。

    import re
    def convert_name_re(name: str) -> str:
        """ 下划线形式字符串转成驼峰形式
        :param name: 下划线形式字符串
        :return: 驼峰形式字符串
        """
        name = re.sub(pattern=r'(_w)',repl=lambda x:x.group(1)[1].upper(),string=name)
        return name
    
    # 这里是测试代码
    print(convert_name_re('go_to_next_page'))  # 'goToNextPage'
    print(convert_name_re('crawl_home_site'))  # 'crawlHomeSite'
    
    
    
    # 反过来是一样的道理
    # p = re.compile(r'([a-z]|d)([A-Z])')
    # sub = re.sub(p, r'1_2', hunp_str).lower() # 这里第二个参数使用了正则分组的后向引用

    注:正则的分组及后向引用详见:python正则表达式系列(4)——分组和后向引用

    注:正则内置属性的用法详见:python正则表达式系列(3)——正则内置属性

  • 相关阅读:
    php-有时候你会疑惑的小问题
    phpDocumentor生成文档
    mongodb重命名集合、数据库
    资料网站
    Service(服务)
    Component(组件)
    Module(模块)
    你不屑于大器晚成,就只能平庸一生
    是狼就磨好牙,是羊就练好腿!
    将Excel数据导入数据库
  • 原文地址:https://www.cnblogs.com/Mint-diary/p/14716921.html
Copyright © 2011-2022 走看看