问题
I´m currently facing the problem that I have a string of which I want to extract only the first number. My first step was to extract the numbers from the string.
Headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
print (re.findall('\d+', headline ))
Output is ['27184', '2']
In this case it returned me two numbers but I only want to have the first one "27184".
Hence, I tried with the following code:
print (re.findall('/^[^\d]*(\d+)/', headline ))
But It does not work:
Output:[]
Can you guys help me out? Any feedback is appreciated
回答1:
Just use re.search
which stops matching once it finds a match.
re.search(r'\d+', headline).group()
or
You must remove the forward slashes present in your regex.
re.findall(r'^\D*(\d+)', headline)
回答2:
Solution without regex (not necessarily better):
import string
no_digits = string.printable[10:]
headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
trans = str.maketrans(no_digits, " "*len(no_digits))
print(headline.translate(trans).split()[0])
>>> 27184
回答3:
re.search('[0-9]+', headline).group()
来源:https://stackoverflow.com/questions/32571348/getting-only-the-first-number-from-string-in-python