简体   繁体   中英

Regular expression to match any number NOT ending in zero

I'm asking for input for a dice game. It really matters whether or not the number entered is divisible by ten.

I have \d+0 for the numbers that DO end in zero.

I need one for the number that DO NOT end in zero.

Thanks in advance.

Maybe this would do the trick

\d*[1-9]

This is not a good use of regular expressions.

I suggest the modulus or integer division operators.

if (number % 10) {
  // number doesn't end in zero
}
\d+[1-9]

Should work, I think.

This will match at least one digit followed by a non-zero digit.

However, you very likely need to embed this in some way, either by anchoring it:

^\d+[1-9]$

to verify that the complete string only contains that number (but then you can also convert said string to a number and do a mod 10).

The way you have it currently (and also the expression in your question) it would match a number like 1203 without problems for both expressions, since regexes match substrings unless you anchor them (except in some environments where they are anchored by default like that – I think Java does that).

Also this works for at least two digits only, as does the expression you posted in your question. I assume that to be intentional. If not, then the + should probably be a * in both cases.

I think

\d*[1-9]

Works better.

I think (d%10==0) is a better way to test divisibility by 10.

If you want use regular expression, try this regular expression

  ^([1-9]+)$  

Using Plain JavaScript var num =temp;

if(temp % 10 !==0){

//your code

}

Divisibility trick is valid for integers not for decimals.

What if someone tris to verify this:

123.120

It ends with a non significant zero.

So 123.12/X and 123.120/X gives same result Same for 123.12%X and 123.120%X (This last is not valid operation since value is not an integer, so can not get module of a float/number)

Module can only be getted for integer values (integer/integer).

And also someone can be trying to look for:

AnyTextWithNumbersNotEndingOnZero_0  <--- Not valid
AnyTextWithNumbersNotEndingOnZero    <--- Valid

So the best an more clear can be somethng like this:

/[0-9]*0$/

Hope helps.

Ah: and if want letters and numbers but last not be a zero:

/[0-9A-Za-z]*0$/

etc

You can try this one to exclude 0

\d+[^0]?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM