Count "(" in a string

I need to do an input text validation which include opening parenthesis and closing parenthesis, what I need to validate is if the opening parenthesis matches closing parenthesis. Here is a sample of the entry text:

thisis(test(of(matching.Text(parenthesis)and)if)working

which one closing parenthesis is missing. I would like to warn the user to correct it before submit.

When I use ListValueCount(form.myValue,“(”)> gives me 0 accourance.
Not sure how could I count the “(” and “)” to compare. Please advice.

use a CFIF to compare Len(Replace(form.myValue,‘(’,‘’,‘all’) and Len(Replace(form.myValue,‘)’,‘’,‘all’)

:slight_smile:

Thanks for the reply. I used the following function to solved the problem:

<cffunction name="countOccurrences" access="public" returntype="numeric" required="true">
<cfargument name="string" type="string" required="True" />
<cfargument name="subString" type="string" required="True" />

<cfset VAR position = findNoCase(arguments.substring,arguments.string,1) />
<cfset VAR count = 0 />

<cfif len(trim(arguments.substring))>
<cfloop condition="position NEQ 0">
<cfset count = count + 1 />
<cfset position = findNoCase(arguments.substring,arguments.string, position + len(trim(arguments.substring))) />
</cfloop>
<cfelse>
<cfreturn 0 />
</cfif>

<cfreturn count />
</cffunction>

Little bit o’ tha RegEX:

<cfset testString = "((asd)))" />

<cfif arrayLen( reMatch( "(\\()", testString ) ) neq arrayLen( reMatch( "(\\))", testString ) )>
    <cfoutput>Mismatched.</cfoutput>
</cfif>

another idea i had was to use ListLen on breaking up the string with ( and ) as delimiters

~anything~ has to be better than looping over the characters one by one and counting them

:cool:

I hear that, Rudy.

When you start out with a language, though, it’s probably natural to feel that this is the easiest solution (to get your head around, though most taxing on the language).

A friend of mine says “Web developers are just problem-solvers. We can all get to the conclusion that 1+1=2, but there are many routes you can take to lead to the same destination.”

For me, I jump at chances like these which teach you sleeker, more optimized and easy to manage code. It’s never too early to develop habits which’ll help you down the road.

yeah, i sorta took to the CF list functions easily…

ListLen(string,‘(’)-1 gives the number of ‘(’ characters

for dealing with query results, i ~love~ ValueList

and in MySQL, there’s SUBSTRING_INDEX, which is awesome

:slight_smile: