Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match the string in $(....) in python

with open('templates/data.xml', 'r') as s:
    for line in s:
    line = line.rstrip() #removes trailing whitespace and '\n' chars

    if "\\$\\(" not in line:
        if ")" not in line:
                continue

    print(line)

    start = line.index("$(")    
    end = line.index(")")

    print(line[start+2:end])

I need to match the strings which are like $(hello). But now this even matches (hello).

Im really new to python. So what am i doing wrong here ?

like image 489
dinesh707 Avatar asked Feb 18 '26 17:02

dinesh707


2 Answers

Use the following regex:

\$\(([^)]+)\)

It matches $, followed by (, then anything until the last ), and catches the characters between the parenthesis.

Here we did escape the $, ( and ) since when you use a function that accepts a regex (like findall), you don't want $ to be treated as the special character $, but as the literal "$" (same holds for the ( and )). However, note that the inner parenthesis didn't get quoted since you want to capture the text between the outer parenthesis.

Note that you don't need to escape the special characters when you're not using regex.

like image 193
Maroun Avatar answered Feb 21 '26 06:02

Maroun


You can do:

>>> import re
>>> escaper = re.compile(r'\$\((.*?)\)')
>>> escaper.findall("I like to say $(hello)")
['hello']
like image 36
arodriguezdonaire Avatar answered Feb 21 '26 07:02

arodriguezdonaire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!