我目前正在使用Python中的RegEx从字符串中删除下划线,如下所示:
def function_renamer(code):
newcode = re.sub('[_](.)', lambda x: x.group(1).upper(), code)在那之后,我想找到有下划线的单词来将它们存储到一个变量中。我可以这么做吗?例如:
function_renamer("def a_random_function(x):")
>> "def aRandomFunction(x):"然后将更改后的字符串"aRandomFunction“存储在变量中。
发布于 2021-01-26 22:04:34
使用这样的方法:
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证明。
结果
def aRandomFunction(x):
['aRandomFunction']表达式扩展
--------------------------------------------------------------------------------
\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 charhttps://stackoverflow.com/questions/65909827
复制相似问题