2

I would like to test a string which should start with any number of digits but not followed by a dot, so I come up these regs, code in jsfiddle:

var startwith = "some string";
    reg1 = new RegExp("^" + startWith + "[0-9]+(?!\\.)"),
    reg2 = new RegExp("^" + startWith + "\d+(?!\\.)");

var text = "11.1";

console.log(reg1.test(text), reg2.test(text)); // result true, false

I started with reg1, but it fails to return the correct result, so I was just trying the reg2. Surprisingly, the result is correct, but what confuses me is that the two regs return different result, while the patterns are basically equivalent. Anybody have any ideas? all thoughts are appreciated.

4
  • does this work for a replacement for reg1? new RegExp("^(0-9)+(?!\\.)") Commented Jul 4, 2014 at 19:53
  • Why are you writing \\., but just \d? What is the difference? Commented Jul 4, 2014 at 19:55
  • @kobi, good question, but with single backslash won't work for some reason, which I don't know. Commented Jul 4, 2014 at 20:00
  • 1
    RegExp constructor requires double slash so \\d instead of \d and \\. instead of \. since it accepts a string in constructor. One backslash is for Javascript string and 2nd one is for Javascript regex engine. Commented Jul 4, 2014 at 20:03

2 Answers 2

1

This should work:

var re = /^\d+(?!\.)\b/;

Problem is that in your regex without word boundary regex matches only first 1 of 11.1 and since next one is not a dot it returns true. You need to force it match till a word boundary is reached.

Online Demo

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

1 Comment

looks promising. will try it.
0

Start with any digit not followed by a dot:

if (/^\d(?!\.)/.test(yourString)) {
    // It matches!
} else {
    // Nah, no match...
}

1 Comment

sorry, not only single digits, but multiple digits.

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.