I need to find a regex expression for a number 1 to 9, followed by trailing zeroes, followed by the end number 1 to 9. As like in a minesweeper game for clearing zeroes.
How do I match the part of an array where like i have 10009 or 2003 ? ,1to9 then zeroes, then 1to9? How would I write it?
does this work? updated: how do I ask this regex or another regex? the one i have below or a (trailing zeroes and 1-9)
(^[1-9][0 ][1-9]$)
CodePudding user response:
[1-9][0] [1-9]
Move the
outside of the square brackets. Otherwise, it will match the literal character.
const regex = new RegExp("[1-9][0] [1-9]")
function test(testCase){
console.log(regex.test(testCase))
}
test("10009")
test("2003")
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
To make the first digit optional, you can do:
[1-9]?[0] [1-9]
const regex = new RegExp("[1-9]?[0] [1-9]")
function test(testCase){
console.log(regex.test(testCase))
}
test("0009")
test("2003")
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
When you say [0 ]
then you are saying that select any of either 0
or
you want is quantifier 0
which means 0 one or more times
You can use ^[1-9]0 [1-9]$
const regex = /^[1-9]0 [1-9]$/;
function test(str) {
return regex.test(str);
}
console.log(test("10009"));
console.log(test("2003"));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>