...

View Full Version : using regular expression to check the string with parentheses



jTrigger
02-20-2003, 04:38 AM
Hi!
I'm having problem in using regular exression when a user entered a string with parentheses. I want the regexp to accept what ever the user entered.

I used this to my incremental search.
e.g.


srcstring = 'sample (x)' // string entered by user

var regExpr = eval("/^" + srcString + "/"); /*regular expression pattern*/


selElementText.search(regExpr) /* search the string in select element*/

here's the error: expected ')' character in regular expresssion.

poccil
02-20-2003, 03:03 PM
The following characters are special in regular expressions and need to be escaped with a backslash:

( ) ? : = [ ] * + { } ^ $ | / , . ! \

This is an escaping function for regular expression strings:



function reescape(str){
var resp="()?:=[]*+{}^$|/,.!\\"
var found=false
var ret=""
for(var i=0;i<str.length;i++){
found=false
for(var j=0;j<resp.length;j++){
if(str.charAt(i)==resp.charAt(j))
{found=true;break}
}
if(found)ret+="\\"
ret+=str.charAt(i)
}
return ret
}


With this function, you can safely escape the string:

var regExpr = eval("/^" + reescape(srcString) + "/");

For your particular application, do this instead:

selElementText.indexOf(srcString) // checks if the string exists

By the way, srcstring is NOT the same as srcString, when it comes to case sensitivity.

jTrigger
02-21-2003, 02:34 AM
Thanks poccil it works, but there's still a problem when i entered a character \.

poccil
02-21-2003, 01:59 PM
Modified previous post.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum