Search code examples
pythonstringstartswith

Regex to return lines starting with specific pattern in a text file


Here is my text file:

    --- config-archive/2022-12-21/R1.txt

+++ new

@@ -1,6 +1,6 @@

 Building configuration...
 
-Current configuration : 1106 bytes
+Current configuration : 1089 bytes
 !
 version 12.4
 service timestamps debug datetime msec
@@ -94,7 +94,7 @@

 !
 !
 !
-banner motd ^Cthis is changed through config pushing script^C
+banner motd ^Cyoyoyoyo i just changed this^C
 !
 line con 0
  exec-timeout 0 0

I need the program to return lines starting with a single - or + from the text file.

My approach is looping through the file and search the pattern as a string which I do not find to be efficient. So need regex to do it in an efficient way. Thank you.


Solution

  • This sounds awfully like an AB question, but here's your solution using RegEx:

    ^[-+].+

    • ^: Matches start of the line
    • [-+]: Matches a minus or a plus
    • .+: Matches any character after that until the end of the line

    Consider using just Python though- it might be faster, and definitely easier to read:

    data = " ... "
    
    lines = [line for line in data.splitlines()
             if line.startswith('+') or line.startswith('-')]