0

I am stuck. I am trying to get rid of the tag and the whitespace between the tag using a regex.

b="<NAME> 
   content here 
   more content
</NAME>
"
result = re.sub("<NAME.*?NAME>", "", b)

If 'b' is all on one line it work. It removes everything between the name tags. But I need it to work with multiple lines as well.

2
  • 1
    Dot never matches newline unless you turn on single-line mode. Commented Mar 22, 2017 at 15:24
  • 1
    Don't use regex to parse XML. Commented Mar 22, 2017 at 15:27

1 Answer 1

1

Your regular expression is not correct. You can use the following regex:

In [7]: print(re.sub(r'\s*</?NAME>\s*', '', b))
content here 
   more content

or:

In [8]: print(re.sub(r'\s*</?NAME>\s*\n', '', b))
   content here 
   more content
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help. Maybe I did not explain myself very good. But what I am trying to accomplish is to get rid of everything between the tags and remove the tags also. The In 7 does remove the spaces and the name tags but it leaves the other characters inbetween.
This is what I have so far. I just need to combine so it is only one. re.sub(r'(.+\s*</?NAME>\s*,'',b); The above removes everything inside the name tag and the </name> tag. I made another regex to remove the first name tag re.sub(r'<name>\s*','',b). How do i combine them?
@user3525290 So can you just add your expected output to your question?
I figured it out. The expected outcome should have been "Left over text". from b="<name> junk in here to remove </name> Left over text". What I wanted to do was remove the name tags and everything inbetween. What I came up with thanks to this help was. re.sub(r'^<name>.?</?name>') however this will only work if <name is at the beginning of the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.