user1952026
user1952026

Reputation: 1

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.

Upvotes: 0

Views: 165

Answers (3)

Abhijit
Abhijit

Reputation: 63707

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

Upvotes: 2

David Robinson
David Robinson

Reputation: 78590

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

If you want to show that part of the string:

print m.groups()[0]

Upvotes: 1

jeremy
jeremy

Reputation: 10047

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.

Upvotes: 1

Related Questions