1

I have the following string:

[TITLE|prefix=a] [STORENAME|prefix=b|suffix=c] [DYNAMIC|limit=10|random=0|reverse=0]

And I would like to get the value of the prefix of TITLE, which is a.

I have tried it with (?<=TITLE|)(?<=prefix=).*?(?=]|\|) and that seems to work but that gives me also the prefix of STORENAME (b). So if [TITLE|prefix=a] will be missing in the string, I'll have the wrong value.

So I need to set the end of the match with ] that belongs to [TITLE. Please notice that this string is dynamic. So it could be [TITLE|suffix=x|prefix=y] as well.

const regex = "[TITLE|prefix=a] [STORENAME|prefix=b|suffix=c] [DYNAMIC|limit=10|random=0|reverse=0]".match(/(?<=TITLE|)(?<=prefix=).*?(?=]|\|)/);
console.log(regex);

1
  • would be awesome if you made it a snippet... would be a lot easier for others to debug ;)
    – Argee
    Sep 16, 2020 at 7:54

2 Answers 2

1

You can use

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

See the regex demo. Details:

  • (?<=TITLE(?:\|suffix=[^\]|]+)?\|prefix=) - a location in string immediately preceded with TITLE|prefix| or TITLE|suffix=...|prefix|
  • [^\]|]+ - one or more chars other than ] and |.

See JavaScript demo:

const texts = ['[TITLE|prefix=a] [STORENAME|prefix=b|suffix=c] [DYNAMIC|limit=10|random=0|reverse=0]', '[TITLE|suffix=s|prefix=a]'];
for (let s of texts) {
  console.log(s, '=>', s.match(/(?<=TITLE(?:\|suffix=[^\]|]+)?\|prefix=)[^\]|]+/)[0]);
}

3
  • So what if the string would be [TITLE|suffix=s|prefix=a]?
    – Proseller
    Sep 16, 2020 at 8:06
  • @Proseller Added to the answer. Sep 16, 2020 at 8:16
  • 1
    Great. Just what I wanted. Thank you!
    – Proseller
    Sep 16, 2020 at 8:17
1

You could also use a capturing group

\[TITLE\|(?:[^|=\]]*=[^|=\]]*\|)*prefix=([^|=\]]*)[^\]]*]

Explanation

  • \[TITLE\| Match [TITLE|
  • (?:\w+=\w+\|)* Repeat 0+ occurrences wordchars = wordchars and |
  • prefix= Match literally
  • (\w+) Capture group 1, match 1+ word chars
  • [^\]]* Match any char except ]
  • ] Match the closing ]

Regex demo

const regex = /\[TITLE\|(?:\w+=\w+\|)*prefix=(\w+)[^\]]*\]/g;
const str = `[TITLE|prefix=a] [STORENAME|prefix=b|suffix=c] [DYNAMIC|limit=10|random=0|reverse=0]
[TITLE|suffix=x|prefix=y]`;
let m;

while ((m = regex.exec(str)) !== null) {
  console.log(m[1]);
}

Or with a negated character class instead of \w

\[TITLE\|(?:[^|=\]]*=[^|=\]]*\|)*prefix=([^|=\]]*)[^\]]*]

Regex demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.