How Nik Broke Up Large Words Found In A String Using Regex

Posted: January 10th, 2012 | Author: | Filed under: Groovy/Grails, Regular Expressions | 4 Comments »

The other day I had a Groovy/Grails bug fix whose solution was to break large non-space ‘words’ (or rather ‘substrings that do not contain spaces’) into smaller words by inserting spaces every X characters.

My regex is not the best, so after a bit of tinkering I reached out to the ever-helpful community over at Stack Overflow. My question was answered within an hour by Nik. I wrapped the solution in a simple function, and modified it to allow you to specify the character length…

static String breakLongWordsInString(str, charLength = 60) {  
	def response  = (str =~ /(\w{${charLength}})/).replaceAll("\$1\n")  
	return response
}

And here’s how it was implemented…

<%@ page import="your.package.path.and.ObjectName" %> 
${TextUtil.breakLongWordsInString(variableName, 60)}

Thanks Stack Overflow and Nik!


4 Comments on “How Nik Broke Up Large Words Found In A String Using Regex”

  1. 1 Peter Boughton said at 5:00 pm on January 10th, 2012:

    You don’t need the parenthesis – you can take them out and use \$0 instead of \$1.

    Also, you might want to consider putting a \b at the end, otherwise if you find something exactly charLength long, you’ll be adding a newline when it probably doesn’t need adding.

    Finally, to actually match “substrings that do not contain spaces”, you want \S instead which matches all non-space characters – the \w only matches alphanumeric and underscore, notably excluding hyphenated words.

  2. 2 Peter Boughton said at 5:53 pm on January 10th, 2012:

    Oops, I should have written \B above, not \b (they perform opposite matches).

    Although, if you did go with the \S route you’d instead need a (?=\S) to perform the same role.

    In summary, I was suggesting:

    def response = (str =~ /\w{${charLength}}\B/).replaceAll(“\$0\n”)

    OR:

    def response = (str =~ /\S{${charLength}}(?=\S)/).replaceAll(“\$0\n”)

  3. 3 Christopher Vigliotti said at 6:19 pm on January 18th, 2012:

    Thanks for the tips, Pete!

  4. 4 Christopher Vigliotti said at 6:19 pm on January 18th, 2012:
    1
    
    // this is only a test

Leave a Reply