Reputation: 6949
Simple regex function that matches the start of a string "Bananas: " and returns the second part. I've done the regex, but it's not the way I expected it to work:
import re
def return_name(s):
m = re.match(r"^Bananas:\s?(.*)", s)
if m:
# print m.group(0)
# print m.group(1)
return m.group(1)
somestring = "Bananas: Gwen Stefani" # Bananas: + name
print return_name(somestring) # Gwen Stefani - correct!
However, I'm convinced that you don't have identify the group with (.*)
in order to get the same results. ie match first part of string - return the remaining part. But I'm not sure how to do that.
Also I read somewhere that you should be being cautious using .*
in a regex.
Upvotes: 1
Views: 5618
Reputation: 36101
You could use a lookbehind ((?<=)
):
(?<=^Bananas:\s).*
Remember to use re.search
instead of re.match
as the latter will try to match at the start of the string (aka implicit ^
).
As for the .*
concerns - it can cause a lot of backtracking if you don't have a clear understanding of how regexes work, but in this case it is guaranteed to be a linear search.
Upvotes: 4
Reputation: 24802
Using the alternate regular expression module "regex" you could use perl's \K
meta-character, which makes it able to discard previously matched content and only Keep the following.
I'm not really recommending this, I think your solution is good enough, and the lookbehind answer is also probably better than using another module just for that.
Upvotes: 1