Reputation: 33
I have the following variable in a string
some_var = ".... \n
... \n
Hello Subject \n
12:34:56:78:90 \n
... \n"
I' m trying to get just the value 123456789
. I tried the following code but gives me next two lines from the line matched.
re.search(r'Subject((.*\n){2})', some_var).group()
Output of above code:
Hello Subject
12:34:56:78:90
Expected output:
12:34:56:78:90
Upvotes: 3
Views: 116
Reputation: 639
A small 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 string and avoids (0x44)
Upvotes: 1
Reputation: 626903
You may do without a regex at all if you do not need to match Subject
as a whole word, and if you do not care about the type of symbols you match on the line below the line having Subject
substring.
Use
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 the Python demo.
Upvotes: 0
Reputation: 1554
This 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));
Upvotes: 0
Reputation: 521419
I don't know what prompted you to choose the pattern you are using, but it looks wrong for extracting that number. Instead, use this pattern:
Subject.*\n(.*?)\n
And then access the matched number using 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)
Upvotes: 3