Proseller
Proseller

Reputation: 133

Getting a part of a dynamic string

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

Answers (3)

The fourth bird
The fourth bird

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=)([^\]|]+))?]

Regex demo

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=)([^|\]*])

Regex demo

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

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

Homer
Homer

Reputation: 429

Try below:

(?<=TITLE\|prefix=)[\w]+|(?<=[\w]+\|suffix=)[\w]+

Explanation:

  • TITLE|prefix= --> Will search for text "TITLE|prefix="
  • ?<= --> will deselect it
  • (?<=[\w]+|suffix=) --> Similarly, will select "suffix=" and anything before it, and will deselect it
  • [\w]+ --> will select word after "TITLE|prefix=" and "suffix="

Upvotes: 1

Related Questions