如何使用正则表达式仅匹配给定字符串中的特定字符?

Ahm*_*med 21 javascript regex

我想要一个特定的值,该值只能是数字并且:

  • 长度应为 11。

  • 第一个数字应该是 0。

  • 第二位数字应该是 1。

  • 第三位数字应该是 0, 1, 2, 5。

  • 然后匹配从第四位到末尾的任何数字。

  • 如果第三位数字是1,则最后两位数字(第10、11)应该相同。

  • 如果第三位是2,则第八位、第九位应该相同。

输入字符串和预期结果。

01012345678          -----> allowed.
0101234a5678         -----> not allowed., letter exists.
01112345688          -----> allowed, 10th, 11st are the same
01112345677          -----> allowed, 10th, 11st are the same
01112345666          -----> allowed, 10th, 11st are the same
01112345689          -----> not allowed..10th, 11st different
01112345-678         -----> not allowed..hyphen exists.
01298765532          -----> allowed..8th, 9th are the same.
01298765732          -----> not allowed, 8th, 9th different.
01298765mm432        -----> not allowed, letter exists.
01500011122          -----> allowed..
020132156456136      -----> not allowed..more than 11 digit.
01530126453333       -----> not allowed..more than 11 digit.
00123456789          -----> not allowed.. second digit not 1.

Run Code Online (Sandbox Code Playgroud)

这是我对 regex101 的尝试,^01[0125][0-9]{8}$ https://regex101.com/r/cIcD0R/1但它忽略了特定情况,也适用于特定情况。

The*_*ird 27

您可以使用 2 个捕获组和反向引用的交替:

^01(?:[05]\d{8}|1\d{6}(\d)\1|2\d{4}(\d)\2\d\d)$
Run Code Online (Sandbox Code Playgroud)

解释

  • ^字符串的开头
  • 01按字面意思匹配
  • (?:替代方案的非捕获组
    • [05]\d{8}匹配0or5和 8 位数字
    • |或者
    • 1\d{6}(\d)\1匹配1,然后是 6 位数字,捕获第 1 组中的单个数字,后跟反向引用以匹配相同的数字
    • |或者
    • 2\d{4}(\d)\2\d\d匹配2,然后是 4 位数字,捕获第 2 组中的单个数字,后跟反向引用以匹配相同的数字并匹配最后 2 位数字
  • )关闭非捕获组
  • $字符串结尾

查看regex101 演示

^01(?:[05]\d{8}|1\d{6}(\d)\1|2\d{4}(\d)\2\d\d)$
Run Code Online (Sandbox Code Playgroud)


3li*_*t0r 15

如果您正在寻找正则表达式,纯粹是为了过滤某些数字而不显示错误消息,那么这个答案可能不适合您。

出于验证目的,正则表达式可能不是最好的方法。如果您使用一个巨大的正则表达式,您将显示一条通用错误消息。这可能会让用户感到困惑,因为他们部分遵守了某些标准。

相反,拆分条件,以便您可以向用户显示相关的错误消息。

function isValid(input, criteria) {
  const errors = [];
  
  for (const [isValid, error] of criteria) {
    if (!isValid(input)) errors.push(error);
  }
    
  return [!errors.length, errors];
}

const criteria = [
  [input => input.length === 11,
    "must have a length of 11"],
  [input => input.match(/^\d*$/),
    "must only contain digits (0-9)"],
  [input => input[0] === "0",
    "must have 0 as 1st digit"],
  [input => input[1] === "1",
    "must have 1 as 2nd digit"],
  [input => ["0","1","2","5"].includes(input[2]),
    "must have 0, 1, 2 or 5 as 3rd digit"],
  [input => input[2] !== "1" || input[9] === input[10],
    "the 10th and 11th digit must be the same if the 3rd digit is 1"],
  [input => input[2] !== "2" || input[7] === input[8],
    "the 8th and 9th digit must be the same if the 3rd digit is 2"],
];

document.forms["validate-number"].addEventListener("submit", function (event) {
  event.preventDefault();
  
  const form = event.target;
  const inputs = form.elements.inputs.value.split("\n");
  
  inputs.forEach(input => console.log(input, ...isValid(input, criteria)));
});
Run Code Online (Sandbox Code Playgroud)
<form id="validate-number">
<textarea name="inputs" rows="14" cols="15">01012345678
0101234a5678
01112345688
01112345677
01112345666
01112345689
01112345-678
01298765532
01298765732
01298765mm432
01500011122
020132156456136
01530126453333
00123456789</textarea>
<br />
<button>validate</button>
</form>
Run Code Online (Sandbox Code Playgroud)


Rav*_*h13 12

对于您显示的示例,请尝试以下正则表达式。这是使用正则表达式的在线演示。

^01(?:(?:[05][0-9]{8})|(?:1[0-9]{6}([0-9])\1)|(?:2[0-9]{4}([0-9])\2[0-9]{2}))$
Run Code Online (Sandbox Code Playgroud)

这是上述正则表达式的 JS 代码,使用foreach循环以及test其中的使用函数。

^01(?:(?:[05][0-9]{8})|(?:1[0-9]{6}([0-9])\1)|(?:2[0-9]{4}([0-9])\2[0-9]{2}))$
Run Code Online (Sandbox Code Playgroud)

说明:添加对所使用的正则表达式的详细说明。

const regex = /^01(?:(?:[05][0-9]{8})|(?:1[0-9]{6}([0-9])\1)|(?:2[0-9]{4}([0-9])\2[0-9]{2}))$/;
[
  "01012345678",
  "0101234a5678",
  "01112345688",
  "01112345677",
  "01112345666",
  "01112345689",
  "01112345-678",
  "01298765532",
  "01298765732",
  "01298765mm432",
  "01500011122",
  "020132156456136",
  "01530126453333",
  "00123456789"  
].forEach(element => 
  console.log(`${element} ----> ${regex.test(element)}`)
);
Run Code Online (Sandbox Code Playgroud)