gpt4 book ai didi

javascript - 如何仅提取没有整个匹配的组作为 String.match() 的输出?

转载 作者:行者123 更新时间:2023-12-01 01:24:30 25 4
gpt4 key购买 nike

我有正则表达式 const EntryRegexp =/^([\d]{1,2})-([\d]{1,2})-([\d]{1,3}) -([\d]{1,2})/;

const pressmark = "1-1-1-1";
const entryRegexp = /^([\d]{1,2})-([\d]{1,2})-([\d]{1,3})-([\d]{1,2})/;
const pressmarkPiecesMatch = pressmark.match(entryRegexp).slice(1);`
// output ["1", "1", "1", "1"] is fine

我可以在没有String.slice的情况下做到这一点吗?我想使用 String.match 并仅获取没有整个匹配 "1-1-1-1" 的组。当 String.match 返回 null 时,使用 String.slice 可能会引发异常。

最佳答案

我不太喜欢我提供的答案,但是创建一个助手或向 String 对象添加原型(prototype)怎么样?

helper

const strictMatch = function (regexp, value) {
return regexp.test(value) ? value.match(regexp).slice(1) : null;
}

//Usage
const pressmark = "1-1-1-1";
const entryRegexp = /^([\d]{1,2})-([\d]{1,2})-([\d]{1,3})-([\d]{1,2})/;
const pressmarkPiecesMatch = strictMatch(entryRegexp, pressmark);

原型(prototype)

String.prototype.strictMatch = function (regexp) {
return regexp.test(this) ? this.match(regexp).slice(1) : null;
}

//Usage
const pressmark = "1-1-1-1";
const entryRegexp = /^([\d]{1,2})-([\d]{1,2})-([\d]{1,3})-([\d]{1,2})/;
const pressmarkPiecesMatch = pressmark.strictMatch(entryRegexp);

关于javascript - 如何仅提取没有整个匹配的组作为 String.match() 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53929554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com