Reputation: 2660
Bit of a regex newbie here. I have this string:
year_with_txt = 'foo 1999'
and
year_only = '1999'
.
I want to omit any 4 consecutive digits. When I do it this way:
re.sub(r'^[0-9]{4}$', '', year_only)
or
re.sub(r'^\d{4}$', '', year_only)
it works. However, with other text in, it doesn't:
re.sub(r'^[0-9]{4}$', '', year_with_txt)
or
re.sub(r'^\d{4}$', '', year_with_txt)
Any suggestions?
Upvotes: 0
Views: 56
Reputation: 19885
The reason is your ^
and $
tokens. Those refer to the start and end of the string respectively.
re.sub(r'\d{4}', '', year_with_txt)
works.
Output:
'foo '
Note: you defined the string as year_with_txt
, but referred to it in the rest of the code as year_with_text
.
Upvotes: 2