首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用RegEx之后,我可以在字符串中获取一个特定的元素并将其存储在变量中吗?

在使用RegEx之后,我可以在字符串中获取一个特定的元素并将其存储在变量中吗?
EN

Stack Overflow用户
提问于 2021-01-26 21:55:41
回答 1查看 47关注 0票数 2

我目前正在使用Python中的RegEx从字符串中删除下划线,如下所示:

代码语言:javascript
复制
def function_renamer(code):
    
    newcode = re.sub('[_](.)', lambda x: x.group(1).upper(), code)

在那之后,我想找到有下划线的单词来将它们存储到一个变量中。我可以这么做吗?例如:

代码语言:javascript
复制
function_renamer("def a_random_function(x):")
>> "def aRandomFunction(x):"

然后将更改后的字符串"aRandomFunction“存储在变量中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-26 22:04:34

使用这样的方法:

代码语言:javascript
复制
import re

results = []

def replace_me(m):
    x = re.sub(r'_(.)', lambda z: z.group(1).upper(), m.group())
    results.append(x)
    return x

def function_renamer(code):
    return re.sub(r'\b[^\W_]+(?:_[^\W_]+)+\b', replace_me, code)

print(function_renamer("def a_random_function(x):"))
print(results)

Python证明

结果

代码语言:javascript
复制
def aRandomFunction(x):
['aRandomFunction']

表达式扩展

代码语言:javascript
复制
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  [^\W_]+                  any character except: non-word characters
                           (all but a-z, A-Z, 0-9, _), '_' (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (1 or more times
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    _                        '_'
--------------------------------------------------------------------------------
    [^\W_]+                  any character except: non-word
                             characters (all but a-z, A-Z, 0-9, _),
                             '_' (1 or more times (matching the most
                             amount possible))
--------------------------------------------------------------------------------
  )+                       end of grouping
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65909827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档