Regex recursion and multiple replacements

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Regex recursion and multiple replacements



I have come across a challenge with regex and could use some assistance. Currently working on a script to update syntax on the source file for plugins by using regex.



Situation:



Without looping a regex search until no match, I am attempting to declare multiple variables as int within functions, since the old syntax did not require it.



For example this is the old code, followed by what I then want it to become
void Split(const char variable, test1, char variable2, test2, test3) {


void Split(const char variable, test1, char variable2, test2, test3) {



void Split(const char variable, int test1, char variable2, int test2, int test3) {


void Split(const char variable, int test1, char variable2, int test2, int test3) {



I have a regex to match a single instance of it here:
(^w.*?)((|, )([w_&]+)(, |))

I could then replace with:
12int 34


(^w.*?)((|, )([w_&]+)(, |))


12int 34





Using regex to parse programming language source is doomed.
– tripleee
Aug 6 at 5:49




2 Answers
2



You can pass a function to re.sub:


re.sub


import re
def update(d) -> str:
return f' intd.group()' if len(re.findall('w+', d.group())) == 1 else d.group()

s = 'void Split(const char variable, test1, char variable2, test2, test3)'
new_s = re.sub('(?<=[,()]).*?(?=[,()])', update, s)



Output:


'void Split(const char variable, int test1, char variable2, int test2, int test3)'



I decided to just go with creating a loop



Edit:


m = re.search(r"((?:^|n)w.*?(?:,s*|())(w+(?:,s*|)))", code, re.M)
while m:
code = re.sub(r"((?:^|n)w.*?(?:,s*|())(w+(?:,s*|)))", r"1int 2", code, re.M)
m = re.match(r"((?:^|n)w.*?(?:,s*|())(w+(?:,s*|)))", code, re.M)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard