Reputation: 16325
If I have a string like this:
*select 65* description
How could I extract the bit after the asterisk and the number using regex in Python? I need something that would yield select
and 65
from the above string.
All of them follow this convention:
*[lowercase specifier] [integer]* description
Upvotes: 0
Views: 161
Reputation: 19047
Python's regex library is powerful, but I'm personally fond of using split() for lighter-weight problems:
>>> s = "*select 65* description"
>>> s.split('*')
['', 'select 65', ' description']
>>> s.split('*')[1].split()
['select', '65']
Upvotes: 1
Reputation: 91069
import re
and then either
m = re.match(r"^\*([a-z]+)\s+([0-9]+)\*\s+(.*)", "*select 65* description")
print m.groups()
or
r = re.compile(r"^\*([a-z]+)\s+([0-9]+)\*\s+(.*)")
m = r.match("*select 65* description")
print m.groups()
depending on the number of matches you want to make. The former is better suited for one or few matches, the latter better for many, because the regex is compiled in a form which is better suited for multiple executions.
Upvotes: 1
Reputation: 129039
You could use this regular expression:
^\*([a-z]+)\s+([0-9]+)\*
In Python, you can match regular expressions with the re
module. Thus:
import re
my_string = """*select 65* description"""
match = re.match(r"^\*([a-z]+)\s+([0-9]+)\*", my_string)
specifier = match.group(1)
integer = int(match.group(2))
Upvotes: 4