Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Something similar to split()?

I'm looking to take a string and break it into an array at line breaks (\n) I tried using split but that takes away the delimiter. I need the \n to be kept at the end of each line if it exists. Does something like this already exist or will I need to code it myself?

like image 627
bwoogie Avatar asked Mar 04 '12 02:03

bwoogie


2 Answers

I tried using split but that takes away the delimiter. I need the \n to be kept at the end of each line if it exists.

You can still use it and preserve the line break if you use look-ahead or look-behind in your regex. Check out the best regular expressions tutorial that I know of:
Regex Tutorial
Look-Around section of the Regex Tutorial.

For example:

public class RegexSplitPageBrk {


   public static void main(String[] args) {
      String text = "Hello world\nGoodbye cruel world!\nYeah this works!";
      String regex = "(?<=\\n)";  // with look-behind!

      String[] tokens = text.split(regex);

      for (String token : tokens) {
         System.out.print(token);
      }
   }
}

The look-ahead or look-behind (also called "look-around") is non-destructive to the characters they match.

like image 101
Hovercraft Full Of Eels Avatar answered Oct 19 '22 23:10

Hovercraft Full Of Eels


Alternative to @Hovercraft solution with Lookahead assertion:

String[] result = s.split("(?=\n)");

Further details about Lookahead in http://www.regular-expressions.info/lookaround.html

like image 36
Anthony Accioly Avatar answered Oct 19 '22 22:10

Anthony Accioly