正则表达式检查第一个数字是否为三位或四位数字。

huangapple go评论51阅读模式
英文:

Regexp three or four digits check for first number

问题

我有数据数字,从101到1056,都以斜杠开头。

我想要正则表达式检查输入是否符合条件。

我所做的是:/^\/[1-9]\d{2,3}$/

我假设[101-1056]不是正确的使用方式? 正则表达式检查第一个数字是否为三位或四位数字。

有没有一种方法可以检查数字是否有四位数,且只能以"1"开头。

英文:

I have data numbers from, say, 101 to 1056. All starting with slash.

I want regexp checking if input suites conditions.

What I did is: /^\/[1-9]\d{2,3}$/

I assume that [101-1056] not the way it should be used? 正则表达式检查第一个数字是否为三位或四位数字。

Is there a way to check if the number has four digits it can start with "1" only.

答案1

得分: 1

你可以将模式写为 ^\/([1-9]\d{2,3})$,使用捕获组来提取数字部分,并在 JavaScript 中比较这些值。

const regex = /^\/([1-9]\d{2,3})$/;
[
  "/101",
  "/456",
  "/1056",
  "/100",
  "/1057",
  "/test"
].forEach(s => {
  const m = s.match(regex);
  if (m) {
    const value = parseInt(m[1]);
    const inRange = value > 100 && value < 1057;
    const text = (inRange ? `` : `not `) + `in range for ${s}'`;
    console.log(text);
  } else {
    console.log(`no match for string '${s}'`);
  }
});
英文:

You can write the pattern as ^\/([1-9]\d{2,3})$ using a capture group for the number part and compare the values in JavaScript.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const regex = /^\/([1-9]\d{2,3})$/;
[
  &quot;/101&quot;,
  &quot;/456&quot;,
  &quot;/1056&quot;,
  &quot;/100&quot;,
  &quot;/1057&quot;,
  &quot;/test&quot;
].forEach(s =&gt; {
  const m = s.match(regex);
  if (m) {
    const value = parseInt(m[1]);
    const inRange = value &gt; 100 &amp;&amp; value &lt; 1057;
    const text = (inRange ? `` : `not `) + `in range for ${s}&#39;`;
    console.log(text)
  } else {
    console.log(`no match for string &#39;${s}&#39;`)
  }
});

<!-- end snippet -->

答案2

得分: 0

不建议使用正则表达式进行数字范围验证。您可以参考以下链接:https://stackoverflow.com/questions/22130429

另外,您可以像这样检查101-109、110-199、200-999、1000-1049和1050-1056分别:^(10[1-9]|1[1-9][0-9]|[2-9][0-9]{2}|10[0-4][0-9]|105[0-6])$

英文:

It's not recommended to use regex for numeric range validation.
https://stackoverflow.com/questions/22130429

BTW, you can have something like this, check for 101-109, 110-199, 200-999, 1000-1049 and 1050-1056 separately.^(10[1-9]|1[1-9][0-9]|[2-9][0-9]{2}|10[0-4][0-9]|105[0-6])$

huangapple
  • 本文由 发表于 2023年3月3日 21:58:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628006.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定