How to check the pattern syntax in a regex

F

François R

I use a regular expression and the user give the pattern it is build
with.
I would like to alert him when the syntax of the pattern is wrong.

if template is the variable that old the pattern, I have tried:
try {
var t = new RegExp(template);

} catch(e) {
window.alert("Bad syntax in regex " + e.message);
}
or variations around
try {
eval( "var t = new RegExp(" + template + ");");

} catch(e) {
window.alert("Bad syntax in regex " + e.message);
}
without success. Either the alert is always given or it never appears.
Thanks for any help on how to do this

François
 
T

Thomas 'PointedEars' Lahn

François R said:
I use a regular expression and the user give the pattern it is build
with.
I would like to alert him when the syntax of the pattern is wrong.

if template is the variable that old the pattern, I have tried:
try {
var t = new RegExp(template);

} catch(e) {
window.alert("Bad syntax in regex " + e.message);
}
OK.

or variations around
try {
eval( "var t = new RegExp(" + template + ");");

} catch(e) {
window.alert("Bad syntax in regex " + e.message);
}
Nonsense.

without success. Either the alert is always given or it never appears.

WFM. Probably you have forgotten to escape special characters before
passing the expression string to RegExp().
Thanks for any help on how to do this

<http://jibbering.com/faq/#posting>


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top