简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM