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!


Regular Expressions, Reverend Jim Ignatowski and You

Posted: July 30th, 2010 | Author: | Filed under: Regular Expressions | 4 Comments »

Regular Expressions

I use regular expressions just often enough to have to totally re-learn them every time I need to use them. After a round of Google searches, reading over a few good regex sites (here’s one) and a bit of head scratching and code tinkering I end up with the code I need.

In this particular case I needed append a variable with punctuation in cases where the variable ended in an alphanumeric character. Regex to the rescue!

1
2
3
4
5
6
7
<cfset variables.question = "what does the yellow light mean" />
<cfif ReFindNoCase("[a-zA-Z0-9]$", variables.question )>
     <cfset variables.question = variables.question & "?" />
</cfif>
<cfoutput> 
     #variables.question #
</cfoutput>

Reverend Jim Ignatowski

This has nothing to do with regular expressions, but it’s a classic moment from Taxi.

You

The next time you need some regex help you may want to check out http://www.regular-expressions.info. If you have any good regex tips or sites leave them in the comments below. As usual, spammers will be shot on site.