1

I would like to split a String using regex just like in this example, but in my case I want that each words in a new line will not exceed X characters.

So the following code doesn't do the trick since it finds every instance of at least X non-newline characters (and not max X).

s = s.replaceAll("(.{" + x + ",}?)\\s+", "$1\n"); 

I can easily do this using other methods, but I would like to do it using a REGEX

2
  • Have you tried: (.{0, " + x + "}) instead? Commented Jul 3, 2013 at 10:24
  • Tried it, but it doesn't work for certain scenarios Commented Jul 4, 2013 at 10:53

1 Answer 1

3

Try this:

s = s.replaceAll("(.{0,"+ x+"})\\b", "$1\n"); 

or the trimmed version,

s = s.replaceAll("(?:\\s*)(.{1,"+ x +"})(?:\\s+|\\s*$)", "$1\n") 
Sign up to request clarification or add additional context in comments.

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.