[英]Regular expression to separate out the last occurring number using Python
I have a regular expression which separates out the number from the given string. 我有一个正则表达式,它将数字与给定的字符串分开。
username = "testuser1"
xp = r'^\D+'
ma = re.match(xp, username)
user_prefix = ma.group(0)
print user_prefix
output is 输出是
testuser
But if the username is something like below 但如果用户名如下所示
username = "testuser1-1"
I am getting the following output 我得到以下输出
testuser
which is expected. 这是预料之中的。 But I am looking for the following 但我正在寻找以下内容
testuser1-
Basically the regular expression should separate out the last occurring whole number (not individual digits). 基本上,正则表达式应该将最后出现的整数(不是单个数字)分开。
Summary is 总结是
input = "testuser1"
>>> output = testuser
input = "testuser1-1"
>>> output = testuser1-
input = "testuser1-2000"
>>> output = testuser1-
Can I have a single regular expression to deal with the above all cases..? 我可以用一个正则表达式来处理上述所有情况吗?
You can use re.sub
and look behind syntax: 您可以使用re.sub
并查看语法:
re.sub(r'(?<=\D)\d+$', '', username)
A shorter version: 更短的版本:
re.sub(r'\d+$', '', username)
The sub
function is more suited for this case. sub
功能更适合这种情况。
Test cases: 测试用例:
re.sub(r'\d+$', '', "testuser1-100")
# 'testuser1-'
re.sub(r'\d+$', '', "testuser1-1")
# 'testuser1-'
re.sub(r'\d+$', '', "testuser1")
# 'testuser'
A solution using re.match: 使用re.match的解决方案:
import re
username = "testuser1"
xp = r'^(.+?)\d+$'
ma = re.match(xp, username)
user_prefix = ma.groups()[0]
user_prefix
# 'testuser'
# you can also capture the last number
xp = r'^(.+?)(\d+)$'
ma = re.match(xp, username)
user_prefix, user_number = ma.groups()
user_prefix, user_number
# ('testuser', '1')
print re.match(xp, "testuser1-2000").groups()
# ('testuser1-', '2000')
re.match(xp, "testuser1-2000").groups()[0]
# 'testuser1-'
re.match(xp, "testuser1-2000").group(1)
# 'testuser1-'
这里!
regex_ = '\w+-?(?:\d+)?'
涉及正则表达式的引擎较少(考虑-
作为唯一的标记)
^([^\s-]+-|\D+)
我建议从最后开始,删除每个字符并停在第一个非数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.