'find word only in single braces using regex in python
I have a string like
text= '{username} joined {servername} {{anytext {find} this {and} this also}} '
and a simple regex code
print(re.findall('{([^{}]*)}', text))
#output
['username', 'servername', 'anytext']
Where anytext
is inside double braces but it is also validating by the regex. I mean, the regex should only find word in single braces and ignore double braces.
Please help me to do this happen.
Solution 1:[1]
Assuming you only expect either {...}
or {{...}}
we can use the following re.findall
trick:
text = '{username} joined {servername} {{anytext}}'
matches = [x for x in re.findall(r'\{\{.*?\}\}|\{(.*?)\}', text) if x]
print(matches) # ['username', 'servername']
The trick here is to match {{...}}
first in the alternation followed by {...}
, while only capturing the second single bracket version. We filter off the empty matches, leaving behind the matches we want.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tim Biegeleisen |