Proseller
Proseller

Reputation: 101

Match only the attribute of the defined tag

I have defined my own tags and attributes, like [TITLE|prefix=X]. Now I would like to get the value of the attribute prefix, which is defined for the tag [TITLE].

This is what I have used:

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

If the string is [TITLE][DYNAMIC|prefix=Y], it works fine, since there is no match but if the string is [TITLE|suffix=X][DYNAMIC|prefix=Y], it gives me the wrong value but it should be no match too.

See https://regexr.com/5gmmq

Upvotes: 2

Views: 34

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You define the tag boundaries with square brackets. So, use them inside a negated character class:

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

See the regex demo. A capturing pattern would be

TITLE[^\][]*\|prefix=([^\]|]+)

Here,

  • (?<=TITLE[^\][]*\|prefix=) - a positive lookbehind that matches a location that is immediately preceded with
    • TITLE - literal string
    • [^\][]* - 0 or more chars other than [ and ]
    • \|prefix= - a |prefix= string
  • [^\]|]+ - one or more chars other than ] and |. In JavaScript regex flavor, the ] inside a character class in the initial position must be escaped.

Upvotes: 1

Related Questions