Can I take a specific element in the string and store it in the variable after using RegEx?

Viewed 47

I'm currently using RegEx in Python to remove the underscores from a string, shown below:

def function_renamer(code):
    
    newcode = re.sub('[_](.)', lambda x: x.group(1).upper(), code)

After that I'd like to find the words that had underscores to store them into a variable. Is it possible for me to do that? For example:

function_renamer("def a_random_function(x):")
>> "def aRandomFunction(x):"

Then store the changed string "aRandomFunction" in a variable.

1 Answers

Use something like:

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)

See Python proof.

Results

def aRandomFunction(x):
['aRandomFunction']

Expression expanation

--------------------------------------------------------------------------------
  \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
Related