简体   繁体   中英

How to find all substrings in a string that starts with {{ and ends with }

How to find all substrings in a string that looks like this one {{ test_variable } ?

s = "hi {{ user }}, samle text, {{ test_variable } 2100210121, testing"

My try:

finds = re.findall(r"(\\{{ .*?\\}$)", s)

but this regex return also substring that ends with }} instead of only } so I see unwanted {{ user }} in result

Try using the following regex pattern:

\{\{\s*([^{} ]+)\s*\}(?=[^}]|$)

This is similar to what you are using, but it makes use of a positive lookahead after the closing } to ensure that what follows is either not another } , or is the end of the string.

\{\{\s*([^{} ]+)\s*\}   match desired string as {{ STRING }
(?=[^}]|$)              then assert that what follows the final } is NOT
                        another }, or is the end of the entire string

Script:

s = "hi {{ user }}, samle text, {{ test_variable } 2100210121, testing"
matches = re.findall(r'{{\s*([^{} ]+)\s*}(?=[^}]|$)', s)
print(matches)

['test_variable']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM