1

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.

4
  • Works for me? refiddle.com/refiddles/5452804275622d61533e0000 Commented Oct 30, 2014 at 18:15
  • 2
    Can you post the code where you are testing it in JavaScript? Commented Oct 30, 2014 at 18:18
  • 1
    Do you need to escape your /'s perhaps? How are you calling it exactly in javascript? Commented Oct 30, 2014 at 18:18
  • How are you constructing the regex in JS? it works fine for me. Commented Oct 30, 2014 at 18:20

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried your solution, but it doesn't seem to be working. Please see the edited post.
I needed to escape the "/", but I did not need to escape the "\s". It appears to be working now. Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.