-1

I'd like to write a python regex to replace the string FARM_FINGERPRINT() and anything inside that method call with the string '0'. For example, for the string:

s = 'FARM_FINGERPRINT(stuff(more stuff()), even more stuff), another_thing()'

The regex should replace it with '0, another_thing()'.

I'd be open to non-regex solutions as well.

Ben Caine
  • 918
  • 2
  • 11
  • 20

1 Answers1

1

Identify the start of the string you intend to match and the first parenthesis in that match (thus initializing p_count as 1). Iterate through the string character by character and add 1 to p_count for every open parenthesis ( and subtract 1 from p_count for every closed parenthesis ). Exit the loop when all open parenthesis have been closed.

s = 'FARM_FINGERPRINT(stuff(more stuff()), even more stuff), another_thing()'

start = 'FARM_FINGERPRINT('

p_count = 1
for idx, i in enumerate(s.split('FARM_FINGERPRINT(')[-1]):
    if i=='(': p_count+=1
    elif i==')': p_count-=1
    elif p_count==0: stop = idx; break

string_to_replace = s[:len(start)+stop]

s = s.replace(string_to_replace, '0')

print(s)

Output:

0, another_thing()
rahlf23
  • 7,918
  • 3
  • 14
  • 44