简体   繁体   中英

regex: find string ending with * or?

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() )

You can try this, Regex Demo

import re

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

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

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