1

I have a multiline string variable which includes multiline of system log like below, and I would like to extract the JSON part only

System 123456
Logs start 2021-07-03 12:00:00
<event> {log_in_json}
<event> {log_in_json}

I using find to search over the string variable but this only allow me to get the first occurrence. Anyone could advise?

start = var.find(<event>)
end = var.find("}}")
extracted_line = var[start:end+len("}}")]
json_str = extracted_line.lstrip(<event>)
print(json_str)

1 Answer 1

1

Using the optional second argument to the find method, we can set the starting point for the search. So, second and following times around, we'll start where we previously found the last match (end), until the method returns -1:

var = '''
System 123456
Logs start 2021-07-03 12:00:00
<event> {log_in_json}
<event> {log_in_json2}
'''

start = var.find('<event>')
while start > 0:
    end = var.find("}", start)
    extracted_line = var[start:end+len("}")]
    json_str = extracted_line.lstrip('<event> ')
    print(json_str)
    start = var.find('<event>', end)
# {log_in_json}
# {log_in_json2}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.