[英]Breaking a string in python if a number is 5 digit long or longer
I know I can break a string in python using: 我知道我可以使用以下命令在python中打破一个字符串:
s = re.split("[0-9]| ", string)[0].strip()
However, I would like to break the string only if I have 5 or more consecutive digits. 但是,如果我有5个或更多连续数字,我想打破字符串。
Ex. 防爆。
Hello1234 => Hello1234
Hello12345 => Hello
How can I achieve this? 我怎样才能做到这一点?
就像是
s = re.split("[0-9]{5,}", string)[0].strip()
Alternatively you can also use re.sub
to remove everything after 5 digits: 或者你也可以使用re.sub
删除5位数后的所有内容:
>>> re.sub('[0-9]{5,}.*', '', 'Hello12345World')
'Hello'
>>> re.sub('[0-9]{5,}.*', '', 'Hello12345')
'Hello'
>>> re.sub('[0-9]{5,}.*', '', 'Hello1234')
'Hello1234'
(\\D)*(?=\\d{5,}) (\\ d)*(?= \\ d {5,})
matches any string with 5 digits+ 匹配5位数+的任何字符串
the first capture group will match your string without the digits 第一个捕获组将匹配没有数字的字符串
http://regexr.com/ will allow you to test regular expressions, and also has a reference guide http://regexr.com/将允许您测试正则表达式,还有一个参考指南
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.