[英]Extract all groups after character with regex
The goal is to extract all the pairs key/value from a string which has the following format:目标是从具有以下格式的字符串中提取所有键/值对:
(&(foo=bar)(goo=car))
or (|(foo=bar)(goo=car)(hoo=dar))
(&(foo=bar)(goo=car))
或(|(foo=bar)(goo=car)(hoo=dar))
I don't know how much groups are there, could be 2, could be 50.
我不知道有多少组,可能是 2 个,可能是 50 个。
I need to extract the operator ( & or | ) and the single params.我需要提取运算符( & 或 | )和单个参数。
I tried the following regex, but it ignores the first group:我尝试了以下正则表达式,但它忽略了第一组:
([|&])((\(.*?=.*?\)))+
How can I get all the groups?我怎样才能得到所有的组?
EDIT编辑
I think I might got it working by applying 2 regexps我想我可以通过应用 2 个正则表达式来让它工作
\(([|&])(.*)\)
this will extract only the content这将只提取内容
(foo=bar)(goo=car)
and this would extract the content这将提取内容
\((.*?)\)
foo=bar, goo=car
let match = null; const regex = /(\([^&|]+?=.+?)\)/g; while (match = regex.exec('(&(foo=bar)(goo=car))')) { console.log(match[0]); }
I managed to do everything as expected我设法按预期做所有事情
@Injectable()
export class QueryService {
regex1: RegExp = new RegExp("^\\(([|&])(.*)\\)");
regex2: RegExp = new RegExp("\\(([&|]\\(.*\\)\\(.*?\\)).*?\\)|\\(.*?\\)", "g");
regex3: RegExp = new RegExp("\\((.*?)\\)");
constructor(){}
decode(query: string): Query {
if (!this.regex1.test(query)) {
console.error("Error while parsing query", query);
return;
}
const matches = query.match(this.regex1);
const parts = {
operator: matches[1] as QueryConditions,
content: matches[2].match(this.regex2)
};
return new Query(parts.operator, this._getQueryFields(parts.content));
}
private _getQueryFields(content: string[]): GenericObject {
const mapped: GenericObject = {};
forEach(content, (g) => {
if (this.regex1.test(g)) {
mapped.group = this.decode(g);
}
else {
//
const pair = g.match(this.regex3)[1].split("=");
mapped[pair[0]] = pair[1];
}
});
return mapped;
}
}
Somewhere in my app在我的应用程序的某个地方
source: string = new Query("&", {
foo: "bar",
goo: "car",
group: new Query("&", {
firstName: "john",
lastName: "doe"
})
}).generate();
decoded: Query = this._queryService.decode(source);
// source = (&(foo=bar)(goo=car)(&(firstName=john)(lastName=doe)))
// decode will produce a map
/* {
operator: "&",
fields: {
foo: "bar",
goo: "car",
group: {
operator: "&",
fields: {
firstName: "john",
lastName: "doe"
}
}
} */
of course I can handle multiple groups at the same level, but for now this is enough.当然,我可以在同一级别处理多个组,但现在这已经足够了。 I'll improve the code gradually.
我会逐步改进代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.