|
Mailing Lists
|
Home / Groups / Regular Expressions (RegEx)
Count word in one line and <enter>Ok, the main regex that will do this is: (?m-s)^.*?(?:WordToCheck).*$ Except CF8 doesn't support the '-s' flag, to prevent '.' matching newlines, so instead I had to do: (?m)^.*?(?:WordToCheck)[^\n]*$ And here's the full code example/test to show it in action: <cffunction name="countLinesWithWord" returntype="Numeric" output="false"> <cfargument name="InputText" type="String"/> <cfargument name="WordRegex" type="String"/> <cfset var Regex = '(?m)^.*?(?:#Arguments.WordRegex#)[^\n]*$' /> <cfset var Matches = rematch(Regex,Arguments.InputText) /> <cfreturn ArrayLen(Matches)/> </cffunction> <cfsavecontent variable="Text"> I have a green apple. I have two apple. Green apple and red apple. I have an orange. My brother has red apple and green apple. I have an orange but my friend give me red apple. I do have orange and two books. The two books are given by my friend. </cfsavecontent> <cfset Text = trim(Text) /> <cfloop index="CurWord" list="apple,red apple,two,two|green,(?:red|green) apple"> <cfoutput><br/>'#CurWord#'=#countLinesWithWord(Text,CurWord)#</cfoutput> </cfloop> Got to rush off now, but let me know if that works as desired, and/or if you want any bits explained. |
February 12, 2012
|
Latest Fusion Authority Articles
|
|||||||||||||||||||||||||||||||||||||||||||||||||