tags:

views:

63

answers:

4

Suppose I have a long java String , I need to wrap all whitespaces (length >=2) with <pre></pre> tag... , How to achieve that ?

ex :

before :
String str = "<font color=\"#000000\">A B  C   D</font>"

after :
<font color=\"#000000\">A B<pre>  </pre>C<pre>   </pre>D</font>

Between A and B is one whitespace , and not wrapped.
Between B and C is two whitespaces , and it is wrapped.
Between C and D is three whitespaces , and it is wrapped,too.

How to achieve that in RegExp ? Thanks a lot !

+1  A: 

That will probably not do what you want... Will a &nbsp; do the job you want? Also, I'd seriously consider replacing spacing with <span style="width: 10px; display: inline-block;"> </span>. Or even a proper table...

Tassos Bassoukos
+1  A: 

why don't you simply set white-space:pre-wrap or white-space:pre as css for the element containing your string? i think this is what you're trying to archive.

(or, even more easy, use &nbsp; instead of ' ' (normal space))

oezi
A: 
    String s = "123 123  123";
    s = s.replaceAll("(  )+", "<pre>$1</pre>");

The String s then contains 123 123<pre> </pre>123

Noel M
+5  A: 

How about a CSS solution using white-space:

white-space: pre

With this sequences of white space are not collapsed. So:

<font color="#000000" style="white-space:pre">A B  C   D</font>
Gumbo
Thank you ... but ... How to add this attribute to each `<font>` tag ?
smallufo
Thank you , I solve this not by regex :`str.replaceAll("<font", "<font style=\"white-space:pre\""));`Thanks a lot!
smallufo
actually, font tags are an evil relic from the 90s. you should also do `str = str.replaceAll("(<\\/?)font([^>]*>)", "$1span$2")` to convert all font tags to span tags.
seanizer
@seanizer: But they are not as evil as trying to parse HTML with a regular expression!
Gumbo