Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Matching string from a file
#4
If you want to be really picky.
with open("test.txt", "r") as file:
    for line in file:
        result = re.match(r"\s*(Start Time {1,2}(\d{1,2}/\d{1,2}/\d{4}) (\d{1,2}:\d{1,2}:\d{1,2} [AP]M))\s*$", line)
        if result:
            print(result.groups())
match() forces pattern to start at the start of line.
r"" makes the pattern a raw string. Don't have to worry about escape sequences.
\s* matches any number of whitespace characters.
() creates groups. This pattern has a group for the "Start Time...PM" part, the date part and the time part.
Start Time matches Start Time.
{1,2} matches one or two spaces.
\d{1,2} matches 1 or 2 digits.
/ matches /.
: matches :.
[AP]M matches AM or PM.
\s*$ matches whitespace up to the end of the line.
tester_V likes this post
Reply


Messages In This Thread
Matching string from a file - by tester_V - Mar-04-2024, 09:07 PM
RE: Matching string from a file - by deanhystad - Mar-04-2024, 10:14 PM
RE: Matching string from a file - by Gribouillis - Mar-04-2024, 10:45 PM
RE: Matching string from a file - by deanhystad - Mar-04-2024, 11:55 PM
RE: Matching string from a file - by tester_V - Mar-05-2024, 01:31 AM
RE: Matching string from a file - by Danishhafeez - Mar-05-2024, 05:46 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 928 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  matching a repeating string Skaperen 2 1,383 Jun-23-2022, 10:34 PM
Last Post: Skaperen
  Matching multiple parts in string fozz 31 7,004 Jun-13-2022, 09:38 AM
Last Post: fozz
  Matching Exact String(s) Extra 4 2,100 Jan-12-2022, 04:06 PM
Last Post: Extra
  Help with python code to search string in one file & replace with line in other file mforthman 26 12,544 Dec-19-2017, 07:11 PM
Last Post: Larz60+
  Searching a text file to find words matching a pattern Micael 3 106,607 Nov-07-2017, 08:52 PM
Last Post: Micael
  Matching Duplicate file names with different extentions wmc326 2 4,139 Aug-07-2017, 11:59 PM
Last Post: wavic
  find cell value with matching regular expression of a row in excel file hruday 4 31,186 Jul-05-2017, 01:02 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020