简体   繁体   English

Python:拆分字符串并保持字符拆分

[英]Python: Splitting a String and Keeping Characters Split On

It's my first day working with regex, and I ran into a problem.这是我第一天使用正则表达式,我遇到了一个问题。 The string i'm trying to manipulate is...我试图操纵的字符串是...

1-11-1111A month and a day and a year.

I'm trying to split into: 1-11-1111 and A month a day and a year using splitstring = re.split(r'(?=\\d+\\d+\\d+\\d)', item) , but the results are 1-11- and 1111 A month a day and a year and i'm not sure where i'm going wrong here based on what i've read.我正在尝试使用splitstring = re.split(r'(?=\\d+\\d+\\d+\\d)', item)拆分为: 1-11-1111A month a day and a year ,但结果是1-11-1111 A month a day and a year ,根据我读过的内容,我不确定我在这里哪里出错了。 Thanks for your time!!谢谢你的时间!!

Couple of options...几个选项...

import re

pattern = re.compile(r'([0-9-]+)([A-Z].*)')

item = '1-11-1111A month and a day and a year.'

splitstring = [pattern.match(item)[1], pattern.match(item)[2]]
print(splitstring)

Output:输出:

['1-11-1111', 'A month and a day and a year.']

Or using @Cary Swoveland's regex with the original split (works if it's a number followed by a capital 'A'...或者将@Cary Swoveland 的正则表达式与原始拆分一起使用(如果它是一个数字后跟大写的“A”,则有效...

splitstring = re.split(r'(?<=\d)(?=A)', item)
splitstring

Output:输出:

['1-11-1111', 'A month and a day and a year.']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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