-1

I'm trying to write a regex for matching a string that starts with a 9, has any number of 9s after the first, followed by zero or more 0s.

So 9 would pass, 99 would pass, 990 would pass, 99990000000 would pass.

But if it includes any character that is not a 9 or a 0, or it includes a 0 between any 9s, it would fail.

991 would fail, 909 would fail, 9900009 would fail.

This is what I've tried:

let regex = /^99*0*/;

But this seems to be letting non- 9or0 characters through, like 91.

The logic I thought I was writing was "starts with a 9, followed by any number of 9s, followed by any number of 0s". That isn't working apparently.

TKoL
  • 13,158
  • 3
  • 39
  • 73
  • 1
    You may want to use the end-string anchor too `^9+0*$`. But maybe JS matching does not even need these anchors? Of that I'm unsure. – JvdV Aug 26 '21 at 16:54
  • 1
    No idea how my question was closed as a dupe for 'match an exact string'. In what world does my description of the problem equate to `one single exact string`? – TKoL Aug 27 '21 at 08:01

4 Answers4

1

Try this regex: /\b(9+|9+0+)\b/;. That's got valid in the required and that's fail on the failed of your message.

  • The \b on begin and end of the regex is because i'm trying with a login text using https://regexr.com/. This can be changed for run only with the string using $ at the end. – Eduardo Oliveira Aug 26 '21 at 16:59
1

You need an end of string anchor.

/^9+0*$/

The regular expression contains

  • a start anchor ^,
  • multiple 9 at least one,
  • none or more 0,
  • an end anchor $.
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

The logic I thought I was writing was "starts with a 9, followed by any number of 9s, followed by any number of 0s".

That's exactly what your regex is doing, it's matching a starting 9 followed by any number (none) of 0, and so 91 validly matches the 9 part. What you're missing is anchoring your regex at the end so it won't allow anything around (or in this case, after) it:

/^9+0*$/
Blindy
  • 65,249
  • 10
  • 91
  • 131
0

Assuming you are parsing a text with multiple possible occurences of the string you are trying to match (and you can't be sure whether these are separated by line breaks), you would have to use the word boundary assertion (\b) instead of beginning (^) and end ($) of input assertions:

/\b9+0*\b/

This regular expression is comprised of:

  • \b: a word boundary
  • 9+: 1 or more 9's
  • 0*: 0 or more 0's
  • \b: a word boundary

And if you want the result array from String.prototype.match() to return all matches within the text, include the global flag:

/\b9+0*\b/g
fwestberg
  • 76
  • 4