Quentin Lamamy
Quentin Lamamy

Reputation: 107

Regex with optional character

I am working on a regex (for php) to match this kind of tag :

I have actually this harcodred regex that work only for the 2nd tag

/{€([\da-zA-Z_-]+:[\da-zA-Z_-]+:[\da-zA-Z_]+)}/

Upvotes: 1

Views: 260

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may use a single-pass regex to get separate : separated values from inside {...}:

preg_match_all('~(?:\G(?!\A):|{€(?=[^{}]*}))\K[\da-zA-Z_-]+~u', $s, $result)

See the regex demo

Details:

  • (?:\G(?!\A):|{€(?=[^{}]*})) - the end of the previous successful match with a : after it (the \G(?!\A): part) OR (|) an opening brace with after it, and then there must be } after 0+ chars other than } (see (?=[^{}]*}) lookahead)
  • \K - match reset operator
  • [\da-zA-Z_-]+ - (the actual match returned) 1 or more letters, digits, _ or - symbols

Upvotes: 1

ScheRas
ScheRas

Reputation: 134

The part of the string starting with : should be repeated 0 - n times, am I right?

It can be done with this

\{\€([\da-zA-Z_-])+(\:[\da-zA-Z\_\-]+)*\}

Second part of the regexp ((\:[\da-zA-Z\_\-]+)*) says "group starting with colon followed by sequence of numbers, characters, underscores and dashes longer than one character should be repeated from 0 to n times in string".

You can play with it here.

Upvotes: 0

Related Questions