Home > Back-end >  Regex to return lines starting with specific pattern in a text file
Regex to return lines starting with specific pattern in a text file

Time:12-22

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.

CodePudding user response:

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('-')]

CodePudding user response:

Try this:

import re

pattern = r'^[- ](?![- ])'  # Match lines that start with a single `-` or ` ` and do not have a `- and  ` immediately after

with open('your_text_file.txt', 'r') as f:
    for line in f:
        if re.match(pattern, line):
            print(line)
  • Related