Question

I am trying to match a complex if else regex pattern using jquery.validation

//My regex

(?=^abc1)(^abc1[-]dba\d*.csv)|(?=^def2)(^def2[-]dba\d*.xls|txt)|(?=^ghi3)(^ghi3[-]dba\d*.xls)|(?=^xyz4)(^xyz4[-]dba\d*.csv)

// Example

abc1-dba.csv

Tried over here : http://www.regexr.com/ it matches

But in the code it is not matching anything.

//I call the validate function inside which :-

rules : {    
  param : {
    required : true,
    pattern: "(?=^abc1)(^abc1[-]dba\d*.csv)|(?=^def2)(^def2[-]dba\d*.xls|txt)|(?=^ghi3)(^ghi3[-]dba\d*.xls)|(?=^xyz4)(^xyz4[-]dba\d*.csv)"
  }
}

doesn't work.

Was it helpful?

Solution

There are some errors in your regex, but the reason it's failing on abc1-dba10.csv is because you're writing the regex as a string literal and you forgot to escape the backslashes. Your \d* should be \\d*.

As for the errors, the most significant one is where you test for .xls or .txt extensions. You need to isolate that part in its own group, like this: \.(?:xls|txt). You also forgot to escape the period, not just in that spot but everywhere. (You would probably never get bitten by that one, but it is a bug.)

Aside from that, you've got way more start anchors (^) than you need, but you left out the end anchor ($) entirely. And those lookaheads aren't doing anything useful. If the string matches the regex ^abc1[-]dba\d*.csv, then of course a lookahead like (?=^abc) at the beginning of the string will succeed. Here's how I would write it:

"^(?:abc1-dba\\d*\\.csv|def2-dba\\d*\\.(?:xls|txt)|ghi3-dba\\d*\\.xls|xyz4-dba\\d*\\.csv)$

If you can use a regex literal instead, use this:

/^(?:abc1-dba\d*\.csv|def2-dba\d*\.(?:xls|txt)|ghi3-dba\d*\.xls|xyz4-dba\d*\.csv)$/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top