java - Split by space but not newline -


i trying convert links in given string clickable a tags using following code :

string [] parts = comment.split("\\s"); string newcomment=null;  for( string item : parts ) try {     url url = new url(item);     // if possible replace anchor...     if(newcomment==null){         newcomment="<a href=\"" + url + "\">"+ url + "</a> ";         }else{         newcomment=newcomment+"<a href=\"" + url + "\">"+ url + "</a> ";         } } catch (malformedurlexception e) {     // if there url not it!...     if(newcomment==null){         newcomment = item+" ";     }else{         newcomment = newcomment+item+" ";     } } 

it works fine for

hi there, click here http://www.google.com ok? 

converting

hi there, click here <a href="http://www.google.com">http://www.google.com</a> ok? 

but when string :

hi there, click   here http://www.google.com   ok? 

its still converting :

hi there, click here <a href="http://www.google.com">http://www.google.com</a> ok? 

whereas want final result :

hi there, click   here <a href="http://www.google.com">http://www.google.com</a>   ok? 

i think including newline character while making split.

how preserve newline character in case ?

i suggest different approach:

string nonewlines = "hi there, click here http://www.google.com ok?"; string newlines = "hi there, \r\nclick here \nhttp://www.google.com ok?"; // string format 2 string variables.  // replaced desired values once "format" method called. string replacementformat = "<a href=\"%s\">%s</a>"; // first round brackets define group starting // "http(s)". second round brackets delimit group lookforward reference // whitespace.  string pattern = "(http(s)?://.+?)(?=\\s)"; nonewlines = nonewlines.replaceall(         pattern,         // "$1" literals group back-references.          // in our instance, reference group enclosed between first         // round brackets in "pattern" string.          new formatter().format(replacementformat, "$1", "$1")         .tostring() ); system.out.println(nonewlines); system.out.println(); newlines = newlines.replaceall(         pattern,         new formatter().format(replacementformat, "$1", "$1")         .tostring() ); system.out.println(newlines); 

output:

hi there, click here <a href="http://www.google.com">http://www.google.com</a> ok?  hi there,  click here  <a href="http://www.google.com">http://www.google.com</a> ok? 

this replace http(s) links anchor reference, whether or not have newlines (windows or *nix) in text.

edit

for best coding practices should set replacementformat , pattern variables constants (so, final static string replacement_format , on).

edit ii

actually grouping url pattern isn't necessary, whitespace lookahead sufficient. well, i'm leaving is, works.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -