Need java Regex to remove / replace XML elements from a specific string

I have a problem getting the correct regular expression. I have below xml as a string

<user_input>
<UserInput Question="test Q?" Answer=<value>0</value><sam@testmail.com>"
</user_input>

Now I need to remove only the xml character from the Answer attribute. So I need the following: -

<user_input>
<UserInput Question="test Q?" Answer=value0value sam@testmail.com"
</user_input>

I tried the following regex but failed: -

str1.replaceAll("Answer=.*?<([^<]*)>", "$1");

its deleting all the text before.

Can anyone help?

+4
source share
3 answers

You need to put ?in the first group to make it not greedy, also you do not need Answer=.*?:

str1.replaceAll("<([^<]*?)>", "$1")

Demo

0
source

httpRequest.send("msg="+data+"&TC="+TC); try to do it

0
source

, Java , .{0,1000}, .

Check out this approach using 2 regular expressions or 1 regular expression and 1 replace. Choose the one that works best (I removed the line break \nfrom the first line of input to show the error with a simple one replace):

String input = "<user_input><UserInput Question=\"test Q?\" Answer=<value>0</value><sam@testmail.com>\"\n</user_input>";
String st = input.replace("><", " ").replaceAll("(?<=Answer=.{0,1000})[<>/]+(?=[^\"]*\")", "");
String st1 = input.replaceAll("(?<=Answer=.{0,1000})><(?=[^\"]*\")", " ").replaceAll("(?<=Answer=.{0,1000})[<>/]+(?=[^\"]*\")", "");
System.out.println(st + "\n" + st1);

Program Output:

<user_input UserInput Question="test Q?" Answer=value0value sam@testmail.com"                                                                                                                                                                          
</user_input>  

<user_input><UserInput Question="test Q?" Answer=value0value sam@testmail.com"                                                                                                                                                                         
</user_input>  
0
source

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


All Articles