正则表达式捕获 PCRE 中除最后 2 个字母之外的字符串

问题描述 投票:0回答:1

我有一个来自这些字符串的字符串 test01、abcd02、xyz05,最后 2 个字符始终是数字。从这些字符串中,我想要一个正则表达式来捕获 test、abcd、xyx。我怎样才能捕捉到它?

regex regex-group pcre
1个回答
2
投票

几个问题:

  • 您的字符串是否可以多于或少于 2 位数字?
  • 如果固定为两位数,那为什么不直接去掉最后 2 位呢? 字符而不使用正则表达式?
  • 是因为我们必须验证输入吗?通常,什么 关于“#@123”?

如果您必须检查它是否以数字结尾,那么就不要 使用评论中提出的解决方案

(.*)..$
作为
.
匹配 任何字符,例如,您都会从“Hello”中得到“Hel”。它 与截断字符串具有相同的效果。

我个人会更精确并考虑到 仅限单词,以避免匹配“12345”或“!#@123”之类的内容。

我建议这样:

/^(\p{L}+)\d+$/u

说明:

  • 最后的
    u
    标志是针对 unicode 的,这样你就可以处理 特殊字符,例如表情符号或其他特殊字符,不 知道您的输入文本是什么。
  • 通过 PCRE,您可以使用 unicode 字符类。 这可以帮助您将任何语言中的单词字符与
    \p{L}
    匹配, 这意味着L字母。它与
    \w
    大致相同,但带有 处理多个代码点序列。
  • 如果字符串末尾必须是数字,则可以使用
    \d+
    。 如果确实必须只有 2 位数字,则将其替换为
    \d{2}

const strings = [
  'test01',  // Ok
  'abcd02',  // Ok
  'test123', // More than 2 digits, perhaps ok also?
  'vidéo05', // Accented chars in the word, ok or not?
  '123456',  // Only digits => should it match? maybe not!
  '####03',  // Not word chars before the digits... hmm, no match.
  'Hello'    // No digits at all... no match.
];

const regex = /^(\p{L}+)\d+$/u;

strings.forEach(string => {
  const match = regex.exec(string);
  if (match) {
    console.log(`Word found in "${string}" is "${match[1]}"`);
  }
  else {
    console.log(`Does NOT match "${string}"`);
  }
});

使用 PCRE,你会得到相同的结果:https://regex101.com/r/bvY3dg/1

© www.soinside.com 2019 - 2024. All rights reserved.