我已经编写了RegEx模式
const PATTERN = /get id\(\) {\s*return '([^']*)'/;
但是找到直到第一个匹配。我添加了 g 标志。
现在,而不是仅获取ID:53d69076,99969076,22269076 来自文字
static get id() {
return '53d69076'
}
static get id() {
return '99969076'
}
static get id() {
return '22269076'
}
我有
'get id() {\n return \'53d69076\'',
'get id() {\n return \'99969076\''
'get id() {\n return \'22269076\''
您能帮我修复我的模式吗(仅获取ID,而不获取完整str)?
答案 0 :(得分:1)
如果要在RegExp中获得所有匹配项:
您必须在周期exec
中调用函数while ((match = myRe.exec(str))
您不应在循环while
中指定正则表达式,它应该是可变的。这是不对的:while ((match = /([0-9]+?)/gm.exec(str)) != null)
您需要指定标志g
,也许还要指定m
。范例:/([0-9]+?)/gm
exec
并从RegExp获取所有匹配项
var str = "static get id() {\n return '99969076'\n} \n static get id() {\n return '888888'\n} \n static get id() {\n return '777777'\n}";
function getArray(str){
let match,
arr = [],
myRe = /static get id\(\) {\s*?return '([0-9]+?)'\s*?}/g;
while ((match = myRe.exec(str)) != null) {
arr.push(match[1]);
}
return arr.length > 0 ? arr : false;
}
console.log(getArray(str));
console.log(getArray(null));
replace
并从RegExp获取所有匹配项
var str = "static get id() {\n return '99969076'\n} \n static get id() {\n return '888888'\n} \n static get id() {\n return '777777'\n}";
function getData(str){
let arr = [];
if (str == null) {
return false;
}
str.replace(/static get id\(\) {\s*?return '([0-9]+?)'\s*?}/g,
function(match, p1, offset, str_full){
return arr.push(p1);
});
return arr.length > 0 ? arr : false;
}
console.log(getData(str));
console.log(getData(null));
console.log(getData('fthfthfh'));
replace
const h = "static get id() {return '99969076'}";
console.log(h.replace(/static get id\(\) {return ('[0-9]+?')}/g, '$1'));
const h = "static get id() {\n return '99969076'\n}";
console.log(h.replace(/static get id\(\) {\s*?return '([0-9]+?)'\s*?}/g, '$1'));
答案 1 :(得分:0)
IUUC:
/return\s+\'(?<yourCapturedGroup>\w+)\'/
您可以使用/ g
使用名为yourCapturedGroup的组来检索ID。编辑: 这是regex101的链接:
https://regex101.com/r/0YQIOh/1