user7276674
user7276674

Reputation: 91

Remove text between two regex special character delimiters

s = '^^^@ """@$ raw data &*823ohcneuj^^^ Important Information ^^^raw data^^^ Imp Info' 

In it, I want to remove texts between the delimiters ^^^ and ^^^.

The output should be "Important Information Imp Info"

Upvotes: 2

Views: 117

Answers (2)

Ryan Williams
Ryan Williams

Reputation: 129

def removeText(text):
     carrotCount = 0
     newText = ""
     for char in text: 
           if(char == '^'):
                 # Reset if we have exceeded 2 sets of carrots
                 if(carrotCount == 6):
                      carrotCount = 1
                 else:
                     carrotCount += 1
           # Check if we have reached the first '^^^'
           elif(carrotCount == 3):
                # Ignore everything between the carrots
                if(char != '^'):
                     continue;
                # Add the second set of carrots when we find them
                else:
                     carrotCount += 1
           # Check if we have reached the end of the second ^^^
           # If we have, we have the message
           elif(carrotCount == 6):
                newText += char
      return newText

This will print "Important Information Imp Info."

Upvotes: 1

Stephen Rauch
Stephen Rauch

Reputation: 49784

You can do this with regular expressions:

import re
s = '^^^@ """@$ raw data &*823ohcneuj^^^ Important Information ^^^raw data^^^ Imp Info'
important = re.compile(r'\^\^\^.*?\^\^\^').sub('', s)

The key elements in this regular expression are:

  1. escape the ^ charater since it has special meaning
  2. use the ungreedy match of .*?

Upvotes: 1

Related Questions