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..?
If you want to split a string that matches a regular expression (regex) instead of perfect match, use the split() of the re module. In re. split() , specify the regex pattern in the first parameter and the target character string in the second parameter.
sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.
In this case, what the whole pattern snippet [^\s]*? means is "match any sequence of non-whitespace characters, including the empty string".
Python has a module named re to work with RegEx. Here's an example: import re pattern = '^a...s$' test_string = 'abyss' result = re. match(pattern, test_string) if result: print("Search successful.") else: print("Search unsuccessful.")
You can use re.sub
and look behind syntax:
re.sub(r'(?<=\D)\d+$', '', username)
A shorter version:
re.sub(r'\d+$', '', username)
The sub
function is more suited for this case.
Test cases:
re.sub(r'\d+$', '', "testuser1-100")
# 'testuser1-'
re.sub(r'\d+$', '', "testuser1-1")
# 'testuser1-'
re.sub(r'\d+$', '', "testuser1")
# 'testuser'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With