regex: find string ending with * or?

Viewed 104

I'm trying to find a regex that matches words ending with either * or(exclusively- not both at once) + and another for the string starting with ?

Here's what I tried:

import re


txt = "~The ?rain in+ spain*"
special = f"\\*+"
special2 = f"\\~"
x = re.search(f"\w*{special}\b", txt) #to find in+ and spain*
x2 = re.search(f"^{special2}\w", txt) #to find ~The

print(x.string, x.group(), x.span() )
print(x2.string, x2.group(), x2.span() )

1 Answers

You can try this, Regex Demo

import re

re.findall("~\w+|\w+(?:\+|\*)", text)

['~The', 'in+', 'spain*']
Related