简体   繁体   中英

split string after 2nd character occurence

This is my string 70354871699YG000_7798419T0000_1 .

I want to get the first part of while disregarding anything that comes after the 2nd underscore.

One solution is to spilit all occurences of '_' and join the first two parts thogether like

string = "70354871699YG000_7798419T0000_1"
splits = re.split(r"_",string)

"_".join(splits[:2])

You could match the first underscore using a negated character [^_] class first matching any char except _ and then match _

Assert the second underscore using a positive lookahead:

^[^_]+_[^_]+(?=_)

Regex demo

if you want to do this using python I would suggest:

string = "70354871699YG000_7798419T0000_1"
string = string.split("_",2)
string = string[2]

Not the best code, but hey it works.

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