Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

python - python上的正则表达式将字符串吐入特定序列(regex on python spiting a string into a specific sequence)

I have a string that may look like CITS/CPU/0218/2305CITS/VDU/0218/2305CITS/KEY/0218/2305 or CITS/CPU/0218/2305CITS/VDU/0218/2305 CITS/KEY/0218/2305 or CITS/CPU/0218/2305 CITS/VDU/0218/2305 CITS/KEY/0218/2305 or CITS/CPU/0218/2305

(我有一个字符串,它可能看起来像CITS/CPU/0218/2305CITS/VDU/0218/2305CITS/KEY/0218/2305CITS/CPU/0218/2305CITS/VDU/0218/2305 CITS/KEY/0218/2305CITS/CPU/0218/2305 CITS/VDU/0218/2305 CITS/KEY/0218/2305CITS/CPU/0218/2305)

I was trying to come up with a regex that would match against a sequence like CITS/CPU/0218/2305 so that I can split any string into a list that matches this case only.

(我试图提出一个正则表达式,该正则表达式将与CITS/CPU/0218/2305类的序列匹配,以便我可以将任何字符串拆分为仅与这种情况匹配的列表。)

Essentially I just need to extract the */*/*/* part into a list from incoming strings My code

(本质上,我只需要将*/*/*/*部分从传入的字符串中提取到列表中,我的代码)

product_code = CITS/CPU/0218/2305CITS/VDU/0218/2305 CITS/KEY/0218/2305
(re.split(r'^((?:[a-z][a-z]+))(.)((?:[a-z][a-z]+))((?:[a-z][a-z]+))(.)(\d+)(.)(\d+)$', product_code))

Any suggestions?

(有什么建议么?)

  ask by sakib11 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using re.findall here:

(在这里尝试使用re.findall :)

inp = "CITS/CPU/0218/2305CITS/VDU/0218/2305CITS/KEY/0218/2305"
matches = re.findall(r'[A-Z]+/[A-Z]+/[0-9]+/[0-9]+', inp)
print(matches)

This prints:

(打印:)

['CITS/CPU/0218/2305', 'CITS/VDU/0218/2305', 'CITS/KEY/0218/2305']

If you only want the first match, then just access it:

(如果您只想要第一个比赛,则只需访问它即可:)

print(matches[0])

['CITS/CPU/0218/2305']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...