0

So I have a bunch of strings that contain a sequence of numbers and dashes:

strings = [
     '32sdjhsdjhsdjb20-11-3kjddjsdsdj435',
     'jdhjhdahj200-19-39-2-12-2jksjfkfjkdf3345',
     '1232sdsjsdkjsop99-7-21sdjsdjsdj',
]

I have a function:

def get_nums():
    for string in strings:
        print(re.findall('\d+-\d+', string))

I want this function to return the following:

['20-11-3']
['200-19-39-2-12-2']
['99-7-21']

But my function returns:

['20-11']
['200-19', '39-2', '12-2']
['99-7']

I have no idea how to return the full sequence of numbers and dashes.

The sequences will always begin and end with numbers, never dashes. If there are no dashes between the numbers they should not be returned.

How can I use regex to return these sequences? Is there an alternative to regex that would be better here?

2 Answers 2

3
def get_nums():
    for string in strings:
        print(re.findall('\d+(?:-\d+)+', string))

This needs to be (?:…) rather than just (…), see https://medium.com/@yeukhon/non-capturing-group-in-pythons-regular-expression-75c4a828a9eb

Sign up to request clarification or add additional context in comments.

Comments

0
import re

strings = [
    '32sdjhsdjhsdjb20-11-3kjddjsdsdj435',
    'jdhjhdahj200-19-39-2-12-2jksjfkfjkdf3345',
    '1232sdsjsdkjsop99-7-21sdjsdjsdj',
]

def get_nums():
    for string in strings:
        print(re.search(r'\d+(-\d+)+', string).group(0))

get_nums()

Output:

20-11-3  
200-19-39-2-12-2  
99-7-21  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.