Reputation: 817
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
Upvotes: 45
Views: 74210
Reputation: 921
In my case I wanted to get the first number in the string and the currency too, I tried all solutions, some returned the number without a dot, others returned the number I did like this
priceString = "Rs249.5"
def advancedSplit(unformatedtext):
custom_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
priceList = []
str_length = len(unformatedtext)
index = 0
for l in range(len(unformatedtext)):
if unformatedtext[l] in custom_numbers:
price = unformatedtext[slice(l, len(unformatedtext))]
currency = unformatedtext[slice(0,l)]
priceList.append(currency)
priceList.append(price)
break
elif index == str_length:
priceList.append("")
priceList.append("unformatedtext")
break
else:
continue
index += 1
return priceList
print(advancedSplit(priceString))
to make sure the list will always has len of 2 I added the elif in case the priceString was just "249.5" because I'm using this in web scrape
Upvotes: 0
Reputation: 624
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
Upvotes: 5
Reputation: 174706
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)
Upvotes: 67