Match the second number that follows the given pattern

I have lines like this

hello 45 blabla 12 100 code 45 13 093bb 

      

I would like to match the second number following the keyword code

(with Python). This example "13"

should be returned.


Here is the solution I found

s = "hello 45 blabla 12 100 code 45 13 093bb "
re.search("code \d+ \d+",s).group(0).split(" ")[-1]
# '13'

      

This works, but there are probably better solutions. I tried to use lookbehind, but I ran into the problem that python doesn't carry over lookbehind of underfunded length (and I don't know the number of digits in the first number that follows code

). I tried this

re.search("(?<=code \d+)\d+",s).group(0)
# raise error, v # invalid expression
# sre_constants.error: look-behind requires fixed-width pattern

      

+3


source to share


4 answers


you can skip re

everything together



>>> a = s.split()
>>> a[a.index('code') + 2]
'13'

      

+3


source


You can make it a little cleaner by putting the desired value in a group.



>>> re.search("code \d+ (\d+)",s).group(1)
'13'

      

+1


source


re.search("code \d+ (\d+)", s).group(1) 

      

must work. The brackets () determine which group you want to capture. Group 0 is the entire text, and the following are groups, numbered in sequence.

+1


source


These are a bit shorter than solutions re.search

:

re.findall('code \d+ (\d+)', s)

      

It will only return back what matches the group defined in ()

+1


source







All Articles