简体   繁体   中英

Finding part of string using regular expressions

I'm pretty new in Python and don't really know regex. I've got some strings like:

a = "Tom Hanks XYZ doesn't really matter"
b = "Julia Roberts XYZ don't worry be happy"
c = "Morgan Freeman XYZ all the best"

In the middle of each string there's word XYZ and than some text. I need regex that will find and match this part, more precisely: from XYZ to the end of string.

Unles there is a specific requirement to do through Regex, a non-regex solution will work fine here. There are two possible ways you can approach this problem

1. Given

a = "Tom Hanks XYZ doesn't really matter"

Partition the string with the separator, preceded with a space

''.join(a.partition(" XYZ")[1:])[1:]

Please note, if the separator string does not exist this will return a empty string.

2.

a[a.index(" XYZ") + 1:]

This will raise an exception ValueError: substring not found if the string is not found

Use the following expression

(XYZ.*)

What this does is start capturing when it sees the letters "XYZ" and matches anything beyond that zero or more times.

m = re.search("(XYZ.*)", a)

如果要显示字符串的那一部分:

print m.groups()[0]

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