简体   繁体   中英

How to assign substring to a variable using regex?

I am trying to extract the language code from a url (eg: /en/blog/first-post/) with this expression [^/]\\w{1} and it works. What I need is to assign it to a variable language_code = re.match('[^/]\\w{1}') However, this doesn't work because I don't want to provide a string to match to as an argument. I just want to get two letters from the string.

at the REPL:

>>> import re
>>> url_string = "/en/blog/first-post/"
>>> re.search('[^/]\w{1}', url_string)[0]
'en'

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