volume one
volume one

Reputation: 7563

Why won't this Regex work in REFind()?

I want to search a string to make sure it doesn't contain any numbers or non-alphabetic characters. From my previous question here a Regex solution was proposed which seems to work using online testing tools. But I can't get it to work in this format:

<cfif REFindNoCase(".*?\\P{IsAlphabetic}.*", FORM.Forename)>
<p>Error, your name contains illegal characters</p>
</cfif>

It just allows illegal strings through without picking up on the illegal characters. So myname1977 seems to be let through without showing the error message. What am I doing wrong?

Upvotes: 1

Views: 336

Answers (1)

John Whish
John Whish

Reputation: 3036

The Reg Exp engine ColdFusion uses doesn't have all the power of Java. Something like this should do it for you:

<cfscript>
input = "विकिपीडि";
writeDump(isValidUsername(input));// YES

input = "विकिपीडि7";
writeDump(isValidUsername(input));// NO

input = "hello";
writeDump(isValidUsername(input));// YES

input = "hel lo";
writeDump(isValidUsername(input));// NO

input = "hello7";
writeDump(isValidUsername(input));// NO


function isValidUsername(input) {
    var pattern = ".*?\P{IsAlphabetic}.*";
    var Matcher = createObject( "java", "java.util.regex.Pattern" )
        .compile( javaCast( "string", pattern ) )
        .matcher( javaCast( "string", input ) );

    return !Matcher.matches();
}
</cfscript>

Update

I posted this in the comments but may be useful so adding it to the answer incase it's of interest:

If you're doing simple matching then strings in Java have built in support for Reg Exp so you should be able to just do this: mystring.matches(".*?\P{IsAlphabetic}.*"); The createObject version is more 'reliable' as CF may change something in the future which breaks it.

Upvotes: 4

Related Questions