Python match a regex with specified exceptions

114 views Asked by At

I'm using Python Fabric, trying to comment all lines in a file that begin with "@", unless that "@" is followed by 2 specific IP addresses. So if the file contains (without the bullets)

  • @hi
  • @IP1
  • some stuff here
  • @IP2

then the resulting file should be (also without the bullets)

  • #@hi
  • @IP1
  • some stuff here
  • @IP2

This is what I have so far:

def verify():
    output = sudo("/sbin/service syslog status")
    #if syslog is running
    if 'is running...' in output:  
        #then set output to the value of the conf file                 
        output = sudo("cat /etc/syslog.conf")  
        #If pattern is matched
        if "@" in output and not "@IP1" and not "@IP2":  
            #read all the lines in the conf file     
            sys.stdout = open('/etc/syslog.conf', 'r+').readlines() 
            #and for every line, comment if it matches pattern 
            for line in sys.stdout:
                if "@" in line and not "@1P1" and not   "@IP2":
                line = "#" + line 
    else:
        print GOOD
else:
    print RSYSLOG

I get that when I say

if "@" in output and not "@IP1" and not "@IP2"

Python is thinking that I am saying "do some thing if there is an @ in the file, but ONLY if you also do not have @IP1 and @IP2." What I'm trying to say is "do some thing to any line starting with an @, except the lines @IP1 and @IP2." Also I know there are other errors in my code, but I'm working on just this now.

thanks.

3

There are 3 answers

3
karthik manchala On

Regex solution:

You can use the following regex to match:

^(?=@(?!(IP1|IP2)))

And replace with #

See DEMO

Code:

re.sub(r'^(?=@(?!(IP1|IP2)))', r'#', myStr)
0
Avinash Raj On

I would do like,

if not "@IP1" in output or not "@IP2" in output:
    if output.startswith("@"):
        // stuff here
0
stevieb On

Check if criteria exists in the glob, and if so, open file, read line-by-line, and use re.sub() to add a # inline to the lines that require it.

import re

ip1 = '1.1.1.1'
ip2 = '2.2.2.2'

fh = open('in.txt', 'r')
f = fh.read()
fh.close()

if re.search(r'(@(?!({0}|{1})))'.format(ip1, ip2), f):
    fh = open('in.txt', 'r')
    for line in fh:
       line = re.sub(r'^(@(?!({0}|{1})))'.format(ip1, ip2), r'#\1', line)
       print(line)

Input file:

@1.1.1.1
@this
@2.2.2.2
@3.3.3.3
@
no @
blah

Output:

@1.1.1.1
#@this
@2.2.2.2
#@3.3.3.3
#@
no @
blah