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
source to share
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
source to share
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 .
source to share