Jump to content

A Simple Regular Expression Question - Why Doesn't This Match?


doug

Recommended Posts

This truly is a simple regular expression question. :)I have a variable theTitle with the value: "Test Group A BTYZ311-1"And a variable courseCode with the value "BTYZ311".I want to see if theTitle contains courseCode followed by a dash followed by 1 or more digits.This is my test:

var matchExp = new RegExp(courseCode + '\-\d+', "i");if (!matchExp.test(theTitle)) {   // do something because theTitle doesn't seem to contain the courseCode plus dash + number}

The problem is the .test() method always returns false, so there must be something wrong with my RegExp.Does anybody happen to see what that might be?Thanks,doug

Link to comment
Share on other sites

Alerting matchExp reveals the problem, and it's one of the reasons I never use the RegExp constructor. It's just counter-intuitive. Everything is fine except for your escape character, which needs to be escaped twice. So \\d+I think in this context that escaping the - character is not necessary. At least, it works for me in FF without being escaped.

Link to comment
Share on other sites

Alerting matchExp reveals the problem, and it's one of the reasons I never use the RegExp constructor. It's just counter-intuitive. Everything is fine except for your escape character, which needs to be escaped twice. So \\d+I think in this context that escaping the - character is not necessary. At least, it works for me in FF without being escaped.
Thanks. That did work! I sort of see why and also don't see why. I thought that RegExp was supposed to take a string and turn it into a regular expression. \d only has one interpretation in a regular expression - a digit. So I thought that was ok as is. In fact, I would have guessed that \\d+ meant "find a backslash, the letter d and a plus sign."But anyway, I'll just try to remember to escape all my backslashes in RegExp from now on.You are right, of course, about \-, but I tend to escape all my punctuation so I don't have to remember which has special meaning and which doesn't.Thanks!doug
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...