Adding sub-regex inside regex to match text after first pipe

Viewed 79

Goal

I'm trying to match two things inside brackets, first the string after dollar, and next optionally string after text.

Text Match 1 Match 2
lorem {{ $name }} ipsus name -
lorem {{ $name | pipe1 | pipe2 }} ipsus name pipe1 | pipe2
lorem {{ $name | singlePipe }} ipsus name singlePipe
lorem {{ $ whitespaceBeforeDollar | singlePipe }} ipsus - -
lorem {{ noDollar | pipe1 | pipe2 }} ipsus - -
lorem {{ $name textWithoutPipe }} ipsus - -
lorem {{$whiteSpace | tolerated}} ipsus whitespace tolerated
lorem {{$whiteSpace|tolerated}} ipsus whitespace tolerated

What I've tried

First part (name after dollar) I can match using: /{{\s*\$\s*([^}| ]+)\s*}}/g (see: regex101)

However I fail at matching the second part. For second part I tried using adding the bold part to first one, but it does not work: /{{\s*\$\s*([^}| ]+)(?:\|\s*((?:(?!{{).)*?)\s*)?\s*}}/g

Question

How can get my regex working or write one that matches both?

I tried to do it in a way so I can remove the part matching 2 and match 1 would continue matching without pipes. And if both exists, it matches both. So something like {{regex-matching-one (<<regex-matching-two>>)}} so I can just remove the second regex inside first one it still works.

I contribute to a non-profit open-source project and will use the regex for it.

1 Answers

You may use this regex to get all expected matches

{{\s*\$([^|\s]+)\s*(?:\|\s*(.+?)\s*)?}}

RegEx Demo

RegEx Details:

  • {{: Match opening {{
  • \s*: Match 0 or more whitespaces
  • \$: Match a $
  • ([^|\s]+): First capture group to match 1+ of any characters that are nor| and whitespace
  • \s*: Match 0 or more whitespaces
  • (?:: Start a non-capturing group
    • \|: Match a |
    • \s*: Match 0 or more whitespaces
    • (.+?): Second capture group to match 1+ of any character
    • \s*: Match 0 or more whitespaces
  • )?: End non-capturing group. ? makes this an optional match
  • }}: Match closing }}
Related