RegEx in Java: how to deal with newline

Viewed 99794

I am currently trying to learn how to use regular expressions so please bear with my simple question. For example, say I have an input file containing a bunch of links separated by a newline:

www.foo.com/Archives/monkeys.htm
Description of Monkey's website.

www.foo.com/Archives/pigs.txt
Description of Pig's website.

www.foo.com/Archives/kitty.txt
Description of Kitty's website.

www.foo.com/Archives/apple.htm
Description of Apple's website.

If I wanted to get one website along with its description, this regex seems to work on a testing tool: .*www.*\\s.*Pig.*

However, when I try running it within my code it doesn't seem to work. Is this expression correct? I tried replacing "\s" with "\n" and it doesn't seem to work still.

6 Answers
String str="I am  a   "+"\n  Man    of  Peace"+"\t"+"   .";

str=str.replaceAll("[\\s|\\t|\\r\\n]+"," ").trim();
System.out.println(str);

This above example works for tabSpaces, newLines, and normal spaces. And I have used the trim method of java.lang.String to remove all the additional spaces in 'str'. I hope this helps you and other amazing people here.

Related