5

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?

2
  • thanks guys! it fixed my problem. I've tried a million times to understand regex, still haven't gotten it down yet. Commented Mar 4, 2012 at 3:47
  • You should really have a look at the tutorial that I've linked to as it's the best regex tutorial that I've seen so far. Commented Mar 4, 2012 at 4:18

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Rather than simply saying "you're doing it wrong" -- why not provide the ... solution?
@debracey: that was the plan all along. I often post an initial answer and then add more to it, in order not to work on questions that get deleted. I hate it when that happens. I also don't like posting code without testing it first.
4

Alternative to @Hovercraft solution with Lookahead assertion:

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

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

Comments

1

Another solution is just adding the delimiters after splitting

String delimiter = "\n" String[] split = input.split(delimiter); for(int i = 0; i < split.length; i++){ split[i] += delimiter; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.