Mar-04-2024, 10:14 PM
(This post was last modified: Mar-04-2024, 10:59 PM by deanhystad.)
Quote:No, there is a snytax error that would prevent the program from running. You cannot have a single backslash at the end of a string literal.if re.search("\s+\Start\s\",el) : # < ------------- el is a line from the file ,,, print(f" START LN {el}")This one prints tons of other lines I do not care about. Confused
You need to protect against "\" being interpreted as the start of an escape sequence. I would use raw strings.
I don't think you fully understand what \ does in a regex pattern. Why are you using \Start in your pattern? \S is "match any non-whitespace character". \T doesn't have a special meaning in a re pattern. That's why you got an error.
Quote:I was sure by using “\s+” would filter the line I wanted but it does not.Putting \s+ at the start of the pattern just forces you to have one whitespace character before Start Time. To ignore lines that contain your pattern as well as other text, include the start (^) and end ($) of string in your pattern. You might want to use "match" instead of "search". Match looks for the entire string to match the pattern. Search is happy if it finds your pattern anywhere in the string.
This might work:
with open("test.txt", "r") as file: for index, line in enumerate(file): result = re.match(r"\s*?(Start Time.*?[A|PM])\s*?$", line) if result: print(f"{index:3}: ({result.start()}, {result.end()}) {result.groups()[0]}")Or you could just strip all the leading and starting whitespace and assume any line that starts with "Start Time" is a line you are looking for.