Charming Robot
Charming Robot

Reputation: 2660

re.sub not replacing if the whole string doesn't match

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

Answers (1)

gmds
gmds

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

Related Questions