Sankalp Singha
Sankalp Singha

Reputation: 4546

How to get specific digits only after a word Python regex?

I have a string like so :

'$."result"."000182"."200"', '$."result"."000490"."200"', '$."result"."000530"."200"'

I want to get an array of the results of the digits after the

"result"."[WANTOGETTHISNUMBER]"."200"

I tried something like this ( example )

test_str = "'$.""result"".""000109"".""200""', '$.""result"".""000110"".""200""', '$.""result"".""000111"".""200""', '$.""result"".""000112"".""200""'"

x = re.findall('[0-9]+', test_str)

print(x)
#['000109', '200', '000110', '200', '000111', '200', '000112', '200']

But I want output as : ['000109', '000110', '000111', '000112']

What is the proper way to achieve this?

Upvotes: 0

Views: 1249

Answers (3)

Roy2012
Roy2012

Reputation: 12503

Here's a regex that takes the excessive quotes into account:

test_str = """ '$.""result"".""000109"".""200""', '$.""result"".""000110"".""200""', '$.""result"".""000111"".""200""', '$.""result"".""000112"".""200""'" """

re.findall(r"result\"\".\"\"(\d+)", test_str)

The result is:

['000109', '000110', '000111', '000112']

Upvotes: 1

CHAVDA MEET
CHAVDA MEET

Reputation: 935

Find numbers of Specific Length in String

To find numbers of specific length, N, is a string, use the regular expression [0-9]+ to find number strings of any length. [0-9] matches a single digit. After you find all the items, filter them with the length specified.

Example 1: Find numbers of specific length in a string

In the following example, we take a string, and find all the 3 digit numbers in that string.

Python Program

` import re s tr = """We four guys, live at 2nd street of Malibeu 521. I had a cash of $248 in my pocket. I got a ticket with serial number 88796451-52.""" #search using regex x = re.findall('[0-9]+', str) print('All Numbers\n',x) #digits of length N N=3 def filterNumber(n): if(len(n)==N):
return True else:
return False
#filter the list finalx = list(filter(filterNumber, x)) print('Final List\n',finalx)

Output

All Numbers ['2', '521', '248', '88796451', '52'].          
Final List ['521', '248']`

Upvotes: -1

sahinakkaya
sahinakkaya

Reputation: 6056

You can use this regex:

>>> re.findall('result\.([0-9]+)', test_str)
['000109', '000110', '000111', '000112']

Upvotes: 4

Related Questions