Python Regex: find all lines that start with '{' and end with '}'

后端 未结 3 869
心在旅途
心在旅途 2021-01-16 03:53

I am receiving data over a socket, a bunch of JSON strings. However, I receive a set amount of bytes, so sometimes the last of my JSON strings is cut-off. I will typically g

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-16 04:13

    Extracting lines that start and end with a specific character can be done without any regex, use str.startswith and str.endswith methods when iterating through the lines in a file:

    results = []
    with open(filepath, 'r') as f:
        for line in f:
            if line.startswith('{') and line.rstrip('\n').endswith('}'):
                results.append(line.rstrip('\n'))
    

    Note the .rstrip('\n') is used before .endswith to make sure the final newline does not interfere with the } check at the end of the string.

提交回复
热议问题