我编写了以下程序
var textRegEx = /.{1,3}/g;
var text = "AUZ01A1";
var woohooMatch = text.match(textRegEx);
var finalResult = woohooMatch.join(' - ')
console.log(finalResult);
给出如下输出:
Output:
AUZ - 01A - 1
我希望输出是AUZ - 01 - A1
。我如何改变textRegEx来实现这一点?我尝试了(2,3}和其他一些东西,但它不起作用。我是javascript和regex的新手。你能帮帮我吗?
您可以使用()
组来匹配3,2,2个字符的模式:
var text = "AUZ01A1";
var textRegEx = /(.{3})(.{2})(.{2})/;
var woohooMatch = text.match(textRegEx);
var [ , ...matches] = woohooMatch;
var finalResult = matches.join(' - ');
console.log(finalResult);
用简单的switch
语句区分6
/7
、8
和其他情况:
function format(string) {
switch (string.length) {
case 6:
case 7:
return string.match(
/^(.{2,3})(.{2})(.{2})$/
).slice(1).join(' - ');
break;
case 8:
return string.match(
/^(.{7})(.)$/
).slice(1).join(' - ');
default:
return string;
}
}
或者,如果您喜欢在简洁函数中使用复杂的正则表达式:
function format(string) {
const match = string.match(/^(?=.{6,8}$)(?:.{7}|.{2,3})(?=(.{1}$|.{2})(.{2})?$)/);
return match ? (match[2] ? match : match.slice(0, -1)).join(' - ') : string;
}
对正则表达式的解释,其余部分留给读者作为练习:
^ # Match at the beginning of string
(?=.{6,8}$) # a string of 6, 7 or 8 characters long, which consists of
(?:.{7}|.{2,3}) # a capturing group of either 7 or 2 to 3 characters
(?= # followed by
(.(?:.|$)) # a second capturing group of a character followed by another or the end of string
(.{2})? # and an optional capturing group of two characters.
$ # right before the end of string.
) #
在regex101.com上试试。
试一试:
function format1(string) {
switch (string.length) {
case 6:
case 7:
return string.match(
/^(.{2,3})(.{2})(.{2})$/
).slice(1).join(' - ');
break;
case 8:
return string.match(
/^(.{7})(.)$/
).slice(1).join(' - ');
default:
return string;
}
}
function format2(string) {
const match = string.match(/^(?=.{6,8}$)(?:.{7}|.{2,3})(?=(.{1}$|.{2})(.{2})?$)/);
return match ? (match[2] ? match : match.slice(0, -1)).join(' - ') : string;
}
// Test cases
const strings = [...'1234567890'].map(
(_, i, a) => a.slice(0, i + 1).join('')
);
console.log(strings.map(format1));
console.log(strings.map(format2));
.as-console-wrapper {
max-height: 100% !important;
}
对于您的格式,您可以使用捕获组的替代。
然后在结果中,删除完整匹配并使用-
连接捕获组注意.
匹配任何字符。如果只想匹配大写字符或数字,可以使用字符类[A-Zd]
^(?:(.{2,3})(..)(..)|(.)(.{7}))$
^
起始字符串(?:
备选项的非捕获组(.{2,3})(..)(..)
3个捕获组,其中第一个组有2或3个字符|
或(.)(.{7})
2个捕获组,其中第一个组有一个字符,第二个组有7个字符
)
关闭非捕获组$
字符串结束
Regex演示
const regex = /^(?:(.{2,3})(..)(..)|(.)(.{7}))$/gm;
const s = `AUZ01A
AUZ01A1
AUZ01A11`;
for (const match of s.matchAll(regex)) {
const result = match.slice(1)
.filter(Boolean)
.join(' - ');
console.log(result);
}