我有一个来自这些字符串的字符串 test01、abcd02、xyz05,最后 2 个字符始终是数字。从这些字符串中,我想要一个正则表达式来捕获 test、abcd、xyx。我怎样才能捕捉到它?
几个问题:
如果您必须检查它是否以数字结尾,那么就不要 使用评论中提出的解决方案
(.*)..$
作为 .
匹配
任何字符,例如,您都会从“Hello”中得到“Hel”。它
与截断字符串具有相同的效果。
我个人会更精确并考虑到 仅限单词,以避免匹配“12345”或“!#@123”之类的内容。
我建议这样:
/^(\p{L}+)\d+$/u
说明:
u
标志是针对 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