繁体   English   中英

关于使用正则表达式的 Javascript 问题

[英]Javascript question regarding the use of regex

我需要为数字 1 到 9 找到一个正则表达式,然后是尾随零,最后是数字 1 到 9。就像在扫雷游戏中清除零一样。

我如何匹配数组的一部分,比如我有 10009 或 2003 ? ,1to9 然后归零,然后 1to9? 我该怎么写?

这行得通吗? 更新:我如何询问这个正则表达式或另一个正则表达式? 我下面的那个或一个(尾随零和 1-9)

(^[1-9][0+][1-9]$) 

[1-9][0]+[1-9]

+移到方括号之外。 否则,它将匹配文字字符。

 const regex = new RegExp("[1-9][0]+[1-9]") function test(testCase){ console.log(regex.test(testCase)) } test("10009") test("2003")

要使第一个数字可选,您可以执行以下操作:

[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")

当您说[0+]您是说选择0+任何一个

你想要的是量词0+这意味着0 one or more times

您可以使用^[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"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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