1

I want to extract a number after every ":" (colon) in a string using python 3.5

my string is:

x= "RTD - Shanghai Indices - STD DLY - Indices - 11054 - ID:1053 (INACTIVE) RTD - SIX Swiss incl. SWX Europe - STD L1 - Equity - 10969 - ID:1096 (INACTIVE)"

I have used:

 re.findall('\d+', x)

but this returns all the number which is:

['11054', '1053', '1', '10969', '1096']

But the final result should be:

[1053, 1096]
2
  • have you tried adding the ":" like that re.findall(":\d+", x) Commented Mar 3, 2018 at 13:50
  • nope, but yes now i just got to know that would help, Thanks Commented Mar 3, 2018 at 14:01

4 Answers 4

3

What about:

re.findall(':(\d+)', x)

Parentheses will match the group you want, and colon before that will match actual literal :. It will return digits which follow :.

>>> import re
>>> x= "RTD - Shanghai Indices - STD DLY - Indices - 11054 - ID:1053 (INACTIVE) RTD - SIX Swiss incl. SWX Europe - STD L1 - Equity - 10969 - ID:1096 (INACTIVE)"
>>> re.findall(':(\d+)', x)
['1053', '1096']
Sign up to request clarification or add additional context in comments.

Comments

1

Youre matching \d+, which is all numbers. If you want to match only numbers with a colon before it, add that to your regex: :(\d+):

>>> import re
>>> x= "RTD - Shanghai Indices - STD DLY - Indices - 11054 - ID:1053 (INACTIVE) RTD - SIX Swiss incl. SWX Europe - STD L1 - Equity - 10969 - ID:1096 (INACTIVE)"
>>> re.findall(r':(\d+)', x)
['1053', '1096']

Comments

1

Search for numbers following a : and convert to integer for your desired output: :

>>> [int(y) for y in re.findall(':(\d+)', x)]
[1053, 1096]

Comments

1

use

re.findall(r'(?<=\:)\d+', x)

Positive Lookbehind (?<=:) Assert that the Regex below matches

: matches the character : literally (case sensitive)

\d+ matches a digit (equal to [0-9])

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed

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.