[英]Extract all groups after character with regex
目標是從具有以下格式的字符串中提取所有鍵/值對:
(&(foo=bar)(goo=car))
或(|(foo=bar)(goo=car)(hoo=dar))
我不知道有多少組,可能是 2 個,可能是 50 個。
我需要提取運算符( & 或 | )和單個參數。
我嘗試了以下正則表達式,但它忽略了第一組:
([|&])((\(.*?=.*?\)))+
我怎樣才能得到所有的組?
編輯
我想我可以通過應用 2 個正則表達式來讓它工作
\(([|&])(.*)\)
這將只提取內容
(foo=bar)(goo=car)
這將提取內容
\((.*?)\)
foo=bar, goo=car
let match = null; const regex = /(\([^&|]+?=.+?)\)/g; while (match = regex.exec('(&(foo=bar)(goo=car))')) { console.log(match[0]); }
我設法按預期做所有事情
@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;
}
}
在我的應用程序的某個地方
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"
}
}
} */
當然,我可以在同一級別處理多個組,但現在這已經足夠了。 我會逐步改進代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.