45

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

5
  • 1
    >>> re.search(r'\d+',Headline).group(0) '27184' Commented Sep 14, 2015 at 18:20
  • print (re.findall(r'^[^\d]*(\d+)', headline )) Commented Sep 14, 2015 at 18:21
  • You're using findall, which finds all the occurrences. By the way, Python regular expressions do not require / characters. Commented Sep 14, 2015 at 18:22
  • Thanks for your feedback guys. Great, it worked Commented Sep 14, 2015 at 19:21
  • Related: stackoverflow.com/questions/1665511/… Commented Oct 8 at 19:55

4 Answers 4

67

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)
Sign up to request clarification or add additional context in comments.

Comments

5
re.search('[0-9]+', headline).group()

Comments

5

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.