I am stuck up with a problem while using Regular Expression.
My requirement is : split a long string into maximum size of 125 letters and then insert a line break in between them.
while splitting, it shouldn’t split between the words. in short, i want to split a string into small strings whose length is 125 or at the end of word before 125th letter. Hope i didnt confused
i used one regexp to solve this, and believe me am an absolute zero in this.
i just got one code and copy pasted 😉
StringBuffer result = null;
while(mailBody.trim().length() > 0){
Matcher m = Pattern.compile("^.{0,125}\\b").matcher(mailBody);
m.find();
String oneLineString = m.group(0);
if(result == null)
result = new StringBuffer(oneLineString);
else
result.append("\n"+ oneLineString);
mailBody = mailBody.substring(oneLineString.length(),
mailBody.length()).trim();
}
this is my code, and it’s working perfectly unless the starting string ends with a full stop(.).
In that case it is giving an error like : No match found.
Please help.
Regards,
Anoop P K
Can you try using the following instead?
Here we use your original match OR we match a string whose total length is 125 characters or fewer. The (?:X) items are non-capturing groups, so that I can use the | operator on the large groups.
(See documentation for the Pattern class here.)
Addendum: @Anoop: Quite right, having sentence-ending punctuation left off on its own line is undesirable behavior. You can try this instead: