Reputation: 1395
This is the regex I am using:
date = "1981-89"
date = re.findall(r'\d+', date)
if the date is 1981-89 this returns [1981],[89]. What do I add to the regex to ignore anything after the dash including the dash itself?
Thanks!
Upvotes: 1
Views: 2102
Reputation: 784998
What do I add to the regex to ignore anything after the dash including the dash itself?
You can use this regex:
date = "1981-89"
date = re.match(r'\d+(?=-)', date).group()
// 1981
(?=-)
is a lookahead that makes sure we are only matching number that is followed by a hyphen.
Upvotes: 0
Reputation: 16711
If you need to use regular expressions, use the first element of a match
search:
re.match(r'(\d+)', date).group() # matching using parenthesis in regex
Upvotes: 3
Reputation: 107287
You can remove it with re.sub
:
>>> re.sub(r'-.*','',date)
'1981'
Upvotes: 2