简体   繁体   English

Javascript正则表达式:匹配子字符串而没有前导零

[英]Javascript Regex: Match substring WITHOUT leading zeros

I'm writing a router for Node.js and trying to figure out how to match integer substrings only when they are without leading zeros. 我正在为Node.js编写路由器,并试图弄清楚如何仅在整数子字符串不带前导零时匹配它们。

This is how a potential route might be written: 这是可能路线的写法:

'/users/[int]/'

And I'm trying to replace only '[int]' with regex which is true when: 我试图用正则表达式仅替换“ [int]”,这在以下情况下是正确的:
•value is integer, •值是整数,
•has no leading zeros. •没有前导零。

/\/users\/(^[1-9][0-9]*)\//.test('/users/12345678/');

'/users/1023/' should return true. '/ users / 1023 /'应该返回true。
'/users/0203/' should return false. '/ users / 0203 /'应该返回false。

Because I'm testing only a portion of the string, it seems that I can't use the ^ caret or $ dollar symbols. 因为我仅测试字符串的一部分,所以似乎无法使用^插入符号或$美元符号。

Wow, stumped by this for hours, then figured it out moments after posting this. 哇,为此困扰了几个小时,然后在发布此消息后立刻想出了。

Looks like the word boundary character is the solution: 看起来单词边界字符是解决方案:

/\/users\/\b[1-9][0-9]*\//.test('/users/1023'); returns true.
/\/users\/\b[1-9][0-9]*\//.test('/users/01023'); returns false.

[edit] [编辑]

That's not it either. 也不是。 It needs to return true for only a single 0. 它仅需返回0即可返回true。

/\/users\/\b[[1-9][0-9]*\//.test('/users/0/'); returns false, should return true.

[edit] [编辑]

I think I solved it: 我想我解决了:

/\/users\/([0-9]|[1-9][0-9]*)\//.test('/users/0/'); returns true

Use a negative look ahead: 负面评价:

/\/users\/(?!0)\d+\//

Or simply assert the first digit is not a zero: 或者只是断言第一个数字不是零:

/\/users\/[1-9]\d*\//

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

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