mattherman
mattherman

Reputation: 466

Why does .NET match my regex but Javascript does not?

I needed a regular expression to match fractions and mixed numbers, but not allow zero for any of the distinct values (whole number, numerator, denominator).

I found a solution that was close to what I needed and modified it a little.

I then tested it on RegexHero which uses the .NET regex engine.

The regular expression matched "1 1/2" as I would expect, but when I tried the same regular expression in Javascript with the .test() function, it did not match it.

My suspicion is that it has something to do with how each engine handles the whitespace, but I'm not sure. Any idea why it matched on one but not the other?

The regular expression was:

^([1-9][0-9]*/[1-9][0-9]*|[1-9][0-9]*(\s[1-9][0-9]*/[1-9][0-9]*)?)$

EDIT:

I tried Jasen's suggestion, but my test is still failing.

var ingredientRegex = /^([1-9][0-9]*\/[1-9][0-9]*|[1-9][0-9]*(\\s[1-9][0-9]*\/[1-9][0-9]*)?)$/;
function isValidFraction(value) {
    return ingredientRegex.test(value);
}

It is being tested with Jasmine.

it("should match a mixed number", function() {
    expect(isValidFraction("2 1/2")).toBe(true);
});

SOLUTION:

It is working now. I needed to escape the "/" characters, but I did not need to escape the "\s" as Jasen suggested.

Upvotes: 1

Views: 97

Answers (1)

Jasen
Jasen

Reputation: 14250

You need to mind your escapes. The \s backslash in the character class needs escaping.

var regex = new RegExp("^([1-9][0-9]*/[1-9][0-9]*|[1-9][0-9]*(\\s[1-9][0-9]*/[1-9][0-9]*)?)$");

var str = "1 1/2";

console.log(regex.test(str));  // true

This method requires different escapes for the / character now.

var regex2 = /^([1-9][0-9]*\/[1-9][0-9]*|[1-9][0-9]*(\s[1-9][0-9]*\/[1-9][0-9]*)?)$/;

console.log(regex2.test(str)); // true

MDN RegExp

Upvotes: 3

Related Questions