Python replaces content between angle brackets (<>)

I want to replace the contents between <>

Example:

input: this & lt; test>

Exit: this is & lt; hh>

So far, I:

 test = 'this is a <test>' test = re.sub(r'\<[^>]*\>', 'hh', test) print (test) 

it will always erase <> and output the result as follows: this is hh. But I want: this & lt; hh>

How can I fix it?

+5
source share
5 answers

As follows from the proposal, one of the solutions is

 newstr = 'hh' test = re.sub(r'\<[^>]*\>', '<' + newstr + '>', test) 

But I suspect a better solution with re .

+3
source

You can use the following:

 hh = re.sub(r'(?!<)[^<]*(?=>)', 'hh', test) 

demo

This uses a negative lookahead to match < before the desired pattern, and a positive lookahead to match > after it without capturing them.

+1
source

When your regular expression is composed, you can put brackets around the parts that you want to capture and call when replacing.

The example below shows this method. To be clear, you first define < and > with parentheses, and between them is a regular expression for the word undefined size. For substitution, you recall the first time you capture an input, then “hh” appears, and then you recall the second instance of the captured input string. Positions are called using the backslash \ , followed by the instance number.

 import re test = "<test>" myre = r'(<)\w*(>)' mysub = r'\1hh\2' newstring = re.sub(myre, mysub, string) 
+1
source

You can use a positive look and look.

 >>> import re >>> test = 'this is a <test>' >>> test = re.sub(r'(?<=<)[^><]*(?=>)', r'hh', test) >>> print test this is a <hh> 

Your regular expression will match these < , > characters. Therefore, it was removed from the final result. But using images, you could prevent the characters from matching each other. Look-arounds are zero-width statements that will not consume any characters.

+1
source
 test = 'this is a <test>' test = re.sub(r'\<[^>]*\>', '<hh>', test) print (test) 

You can just do it.

+1
source

Source: https://habr.com/ru/post/1204529/


All Articles