Reputation: 123
I need a regex to remove the spaces between the beginning and the end of xml tags. For example: Someone create the xml and send it to me, so i can validate, sign and send to a webservice.
To do this i need to remove the spaces between the beginning and the end of the tags:
String xmlString = "<?xml version="1.0" encoding="UTF-8"?><car><name>Beatle </name>"
+ "<doors>2</doors><drivers><driver><name> Guilherme</name></driver>"
+ "<driver><name>Leonardo </name></driver></drivers></car>";
xmlString = xmlString.replaceAll("> ", ">");
xmlString = xmlString.replaceAll(" <", "<");
Is there a way to turn this two replaces into one with regex?
Upvotes: 3
Views: 1807
Reputation: 67988
(>) | (<)
You can use |
or
operator and replace by $1$2
.Done in 1 regex.
Upvotes: 1
Reputation: 627468
You can use this regex:
(<[^/][^>]*>) +| +(<\/[^>]+>)
(In Java, this should be used like String pattern = "(<[^/][^>]*>) +| +(<\\/[^>]+>)";
)
And apply the following replacement string:
$1$2
Check Replace, Global.
Tested against:
<?xml version="1.0" encoding="UTF-8"?><car><name>Beatle </name>
<doors>2</doors><drivers><driver><name> Guilherme</name></driver>
<driver><name>Leonardo </name></driver></drivers></car>
Output:
<?xml version="1.0" encoding="UTF-8"?><car><name>Beatle</name>
<doors>2</doors><drivers><driver><name>Guilherme</name></driver>
<driver><name>Leonardo</name></driver></drivers></car>
Upvotes: 2