Reputation: 115
I have a string ("1x5y") from which I want to extract the numbers, but I want to extract those numbers based on the letter. From my string I want to end up with x = 1 and y = 5.
Also, either x or y may or may not be present in the string, but at least one of them will always be present (and only once, not more than once).
I managed to do this with regex and a few "if"s, but I was wondering if there is a more elegant solution.
Thank you
EDIT: here is what I have
delta = "2y"
if ("x" in delta) and ("y" in delta):
x = re.findall('\d+',str(re.findall('\d+x',delta)))
y = re.findall('\d+',str(re.findall('\d+y',delta)))
elif ("x" in delta) and ("y" not in delta):
x = re.findall('\d+',str(re.findall('\d+x',delta)))
elif ("x" not in delta) and ("y" in delta):
y = re.findall('\d+',str(re.findall('\d+y',delta)))
else:
x = y = 0
Upvotes: 0
Views: 102
Reputation: 81604
The most basic and naive regex to solve this is (\d+)([a-zA-Z])
, and there's no need for any if
s. The capturing groups will take care for "associating" each number to the letter on the right of it.
import re
regex = re.compile(r'(\d+)([a-zA-Z])')
for string in ['1x5y', '1x', '5y', '111x2y333z']:
print(string)
for number, letter in regex.findall(string):
print(number, letter)
print()
Outputs
1x5y
1 x
5 y
1x
1 x
5y
5 y
111x2y333z
111 x
2 y
333 z
Upvotes: 1
Reputation: 31060
You can precompile the regex and assign with findall()
import re
s = "1x5y"
p = re.compile(r'(\d+)x(\d+)y')
(x, y) = re.findall(p, s)[0]
Upvotes: 0