Reputation: 133
I have the following dynamic string:
[TITLE|prefix=a] [STORENAME|prefix=s|suffix=s] [DYNAMIC|limit=10|random=0|reverse=0]
And I would like to get the value a from [TITLE|prefix=a] and the value s from [STORENAME|prefix=s|suffix=s].
To get the prefix value of TITLE, I have tried it with result.match(/prefix=*\||\]/)
but I'm not getting what I need.
Upvotes: 0
Views: 138
Reputation: 163457
You could start by matching [
and uppercase chars A-Z. then match |prefix
followed by capturing in a group what you want to keep.
Then optionally match |suffix
and use another group to capture what you want to keep.
\[[A-Z]+\|(prefix=)([^\]|]+)(?:\|(suffix=)([^\]|]+))?]
const regex = /\[[A-Z]+\|(prefix=)([^\]|]+)(?:\|(suffix=)([^\]|]+))?]/g;
const str = `[TITLE|prefix=a] [STORENAME|prefix=s|suffix=s] [DYNAMIC|limit=10|random=0|reverse=0]`;
let m;
while ((m = regex.exec(str)) !== null) {
console.log(`key: ${m[1]}`)
console.log(`value: ${m[2]}`)
if (m[3] !== undefined) {
console.log(`key: ${m[3]}`)
console.log(`value: ${m[4]}`)
}
}
If [TITLE
has to be on the left, you might also use a positive lookbehind with an infinite quantifier to get the matches:
(?<=\[TITLE\|.*)(prefix=|suffix=)([^|\]*])
const regex = /(?<=\[TITLE\|.*)(prefix=|suffix=)([^|\]*])/g;
const str = `[TITLE|prefix=a] [STORENAME|prefix=s|suffix=s] [DYNAMIC|limit=10|random=0|reverse=0]`;
let m;
while ((m = regex.exec(str)) !== null) {
console.log(`key: ${m[1]}`)
console.log(`value: ${m[2]}`)
}
Upvotes: 1
Reputation: 3220
You could try following regex.
(?<=prefix=).*?(?=]|\|)
Details:
(?<=prefix=)
: Lookbehind - matches string after the characters prefix=
.*?
: matches any characters as few as possible(?=]|\|)
: gets any characters until ]
or |
I also tried to run code on javascript.
var string = "[TITLE|prefix=a] [STORENAME|prefix=s|suffix=s] [DYNAMIC|limit=10|random=0|reverse=0]";
var res = string.match(/(?<=prefix=).*?(?=]|\|)/g);
console.log(res);
Upvotes: 1
Reputation: 429
Try below:
(?<=TITLE\|prefix=)[\w]+|(?<=[\w]+\|suffix=)[\w]+
Explanation:
Upvotes: 1