Return the next search string

I have the following variable in line

some_var = ".... \n
... \n
Hello Subject \n
12:34:56:78:90 \n
... \n"

      

I am trying to get just the value 123456789

. I tried the following code but gave me the next two lines from a string.

re.search(r'Subject((.*\n){2})', some_var).group()

      

Output of the code above:

Hello Subject
12:34:56:78:90

      

Expected Result:

12:34:56:78:90

      

+3


source to share


4 answers


I don't know what prompted you to choose the template you are using, but it doesn't look right to extract that number. Use this pattern instead:

Subject.*\n(.*?)\n

      

And then access the matching number with group(1)

which is the first (and only) matched capture group.

some_var = ".... \n... \nHello Subject \n12:34:56:78:90 \n... \n"
print re.search(r'Subject.*\n(.*?)\n', some_var).group(1)

      



Demo

+3


source


Slight modification to Tim's answer:

some_var = ".... \n... \nHello Subject \n12:34:56:78:90 (0x44) \n... \n"
print re.search(r'Subject.*\n(\S+)', some_var).group(1)

      



Explanation: \S+

= gets the first line and escapes(0x44)

Demo

+1


source


It might work.

import re;
some_var = ".... \n... \nHello Subject \n12:34:56:78:90 \n... \n";
# you might want to try \r too if its required with \n
s = re.search('Subject[\ ]*\n([\d:]+)', some_var);
if s:
    print(s.group(1));

      

0


source


You can do without the regex at all if you don't need to match Subject

as a whole word, and if you don't need the type of characters that match the line below the Subject

substring line.

Using

some_var = ".... \n    ... \n    Hello Subject \n    12:34:56:78:90 \n    ... \n"
lst = some_var.split("\n")              # Split at newline
cnt = len(lst)                          # Get the item count
for idx, line in enumerate(lst):        # Enumerate lst to access index + item
    if "Subject" in line and idx < cnt - 1: # If not at end and line has "Subject"
        print(lst[idx+1].strip())       # Strip from whitespace and print next line

      

See Python demo .

0


source







All Articles