我写过RegEx模式
const PATTERN = /get id\(\) {\s*return '([^']*)'/;但它会在第一场比赛前找到。我添加了g标志。
现在不再只是从文本中获得ids: 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\''你能帮我修复我的模式(只得到ids,而不是完整的str)吗?
发布于 2019-04-11 20:55:53
IUUC:
/return\s+\'(?<yourCapturedGroup>\w+)\'/可以使用名为yourCapturedGroup的组使用/g检索ID
编辑:下面是regex101的链接:
https://regex101.com/r/0YQIOh/1发布于 2019-04-11 21:08:36
JavaScript RegExp全匹配
如果您想在RegExp中获得所有匹配:
exec中调用函数while ((match = myRe.exec(str))while ((match = /([0-9]+?)/gm.exec(str)) != null)g,或者指定m。Exapmle:/([0-9]+?)/gm示例如何在exec中使用函数JavaScript并从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中使用函数JavaScript并从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中使用函数JavaScript的其他示例
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'));
https://stackoverflow.com/questions/55640828
复制相似问题