简体   繁体   中英

regular expression re.sub for string formatting in python

Quite new to regular expressions and am trying to get a grasp on them

string = "regex_learning.test"
subbed = re.sub(r'(.*)_learning(.*), r'\1', string)

What I was hoping for is "regex.test" as an ouput when printing subbed , however I just get "regex"

Could someone explain why I am losing the .test?

Thanks in advance

Use this:

subbed = re.sub(r'(.*)_learning(.*)', r'\1' + r'\2', string)

You can also write it as:

subbed = re.sub(r'(.*)_learning(.*)', "%s%s" % (r'\1', r'\2'), string)

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