TypeScript 正则表达式提取字符串前两位字母和后12个字符
可以使用正则表达式 ^(.{2}).{12}(.{12}) 来匹配字符串中前两个字母和后12个任意字符。
具体代码示例:
const str = 'FE230822B00012-000000001866B5';
const regex = /^(.{2}).{12}(.{12})/;
const matches = regex.exec(str);
if (matches) {
const firstTwoLetters = matches[1]; // 前两个字母
const lastTwelveChars = matches[2]; // 后12个任意字符
console.log(firstTwoLetters); // 输出 'FE'
console.log(lastTwelveChars); // 输出 '000000001866B5'
} else {
console.log('匹配失败');
}
在上述代码中,我们使用 exec 方法来执行正则表达式的匹配,如果匹配成功,则通过 matches 数组获取匹配到的结果。其中,matches[1] 表示第一个括号捕获到的结果,即前两个字母;matches[2] 表示第二个括号捕获到的结果,即后12个任意字符。
原文地址: https://www.cveoy.top/t/topic/w7y 著作权归作者所有。请勿转载和采集!