# Reducing number of blank spaces

This program takes blank spaces before some chars like > < />, and if there is more than one blank space in the line, it will reduce to one.

return source.replaceAll("\\s{2,}", " ").replaceAll("[[\\>][\\s]][[\\s][\\>]]", ">").replaceAll("[[\\<][\\s]][[\\s][\\<]]", "<").replaceAll("[\\s][/>]", "/>");


How can I improve my regex code?

My test code is:

<?xml version="1.0" encoding="UTF-8"?>
<nfeProc xmlns="http://www.portalfiscal.inf.br/nfe"  versao="2.00" >
<protNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="2.00"><infProt><tpAmb>1</tpAmb><verAplic>13_0_94</verAplic><chNFe>31130821483359001109550010002217051649842350</chNFe><dhRecbto>2013-08-07T01:52:47</dhRecbto><nProt>131131174998806</nProt><digVal>JOjHIJzegFkL7ZfGkfAgSwP0+s4=</digVal><cStat>100</cStat><xMotivo>Autorizado o uso da NF-e</xMotivo></infProt></protNFe>
</nfeProc>

• Why do you need this? If you have a decent XML-parser then does it really matter how many spaces there are before >-characters? Because you DO use a XML-parser to parse your XML data, don't you? – Simon Forsberg Nov 12 '13 at 0:16
• because some documents have \n and I want to take it off. – Diego Macario Nov 12 '13 at 11:50
• Why? What harm has \n ever done to you? – Simon Forsberg Nov 12 '13 at 12:33
• can brake the string sequence – Diego Macario Nov 12 '13 at 13:44

source.replaceAll("\\s+([<> ]|/>)", "$1");  • I know this is pretty simple but would you please try to explain it a little bit? – Malachi Nov 12 '13 at 13:48 • \O/ so fine, could you suggest to me some reading to know about regex? Because I want to know about $1 and how do you generate this image? – Diego Macario Nov 12 '13 at 13:50