-1

This is my problem:

234 is valid 230 is not valid

For this, I've used this regex : ^[0-9]+[^0]$ but it didn't work. I tried to change this regex for : ^[1-9]+[^0]$

26660 it's Ok it's not valid but 2066 it's not ok because of [1-9].

Thanks!

Tom
  • 1
  • 1

2 Answers2

2

I'm going to take a gamble answering this, since your question isn't really all that clear.

Anyway, it helps if you rephrase the Regex in plain english. In your case:

^[0-9]+[^0]$

Which reads as: it has to start with at least one character 0-9, as many times as possible... followed by any character other than a 0, which must be the end of the string as well.

Which almost assuredly isn't what you want. After all, '123a' is a match (the last character isn't a 0.) And '3' isn't a match, even though you probably want it to match.

So, if what you're looking for is 'Any number that doesn't end in a '0', then...

^[0-9]*[1-9]$

How does that translate to english? Any number of characters 0-9 (and that includes no characters) followed by a character 1-9, which ends the string.

Two very useful things to do when working with Regex:

  • Google 'Regex Online' - there are a number of online regex testers.
  • Google 'Regex Cheat Sheet' - there are a number of quick guides on how to compose regex.
Kevin
  • 2,041
  • 7
  • 20
0

Your regex is right. What language do you use?

You can try Regex online by this website.

Online regex

And I use it to check your regex, it ran well.

Chih Sean Hsu
  • 203
  • 1
  • 9
  • Thanks Chih Sean Hsu, you're wright. I didn't pay enough attention on Online regex. It's just that when I tried so, it shows me that is valid (230) when I pressed ENTER. – Tom May 18 '20 at 16:24
  • @Tom: that's because most of the online-regex testers support multiline input. If you press enter a linebreak \n will be appended to the string. So the string you test against would be "230\n" which then of course would match your regular expression. – oRole May 18 '20 at 16:31