liv2luv
liv2luv

Reputation: 37

JavaScript Regex pattern - baffled

I am using XSLT with regexp:match exslt function. The said function takes JavaScript Regex pattern. Therefore I am trying to match a set of numbers 1 thru 3 OR 5 thru 7 OR 9 thru 23.

Following is the regex pattern I've come up with:

(^[1-3]$|^[5-7]$|^[9-23]{1,2}$)

This regex does NOT match with any value at all. Following alternate pattern is good only to a little extent:

(^[1-3]$|^[5-7]$|^9$|^[10-23]{2}$)

While this matches with all other expected number values except 14 thru 19. Why is it so and how to make the Regex good. BTW, I am using http://www.regextester.com/ to test the pattern matching.

Thank you.

Upvotes: 0

Views: 113

Answers (4)

thejh
thejh

Reputation: 45578

Brackets contain characters, not strings. Try this:

^([1-35-79]|1[0-9]|2[0-3])$

Edit: Tested it, it works.

var str="";
for (var i=0; i<30; i++) {
  if (/^([1-35-79]|1[0-9]|2[0-3])$/.test(i+"")) str+=i+' '
}
console.log(str);

prints

1 2 3 5 6 7 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Upvotes: 2

Jonathan M
Jonathan M

Reputation: 17451

Convert it to an integer, test for >0 and < 24 and !=4 and !=8. Keep it simple.

Upvotes: 0

Joe
Joe

Reputation: 82654

You are working with strings not numbers so 14 or 19 or 20 are strings of digits not the numbers.

so [10-23]{2} will match 0-2, 1,3 or 0,1,2,3 two times. Notice the missing 4-9.

(^[1-3]$|^[5-7]$|^9$|^1[0-9]$|^2[0-3]$)

Upvotes: 0

user554546
user554546

Reputation:

In regexes, stuff in brackets only denotes one character. Try:

^[1-3]$|^[5-7]$|^9$|^1[0-9]$|^2[0-3]$

Upvotes: 0

Related Questions