OnStandBy
OnStandBy

Reputation: 79

Regex for "{ [string] }" or "{{ [string] | [string] }}"

I'm working on a contract generator in french which search for things between "{ }" and replace them but I can't make one that will fit my needs.

Here's an example :

**Nom de l'{{apprenti | apprentie}}** : {train_PrenomPersonne} {train_NomPersonne}

The double brackets must be replaced by one of the two propositions in it, depending on gender. The single brackets must be replaced by values form the database.

So the final result should be :

**Nom de l'apprenti** : Chuck Norris

Will it be simpler to makes two differents regex for each case because they're not used the same way or a single one could fit ?

I just need a correct regex, the best result I could get by myself is a single match between the first and the last brackets.

Upvotes: 1

Views: 57

Answers (1)

Jan
Jan

Reputation: 43169

You could use

{{1,2}
(?P<group1>[^{}|]+)\s*
(?:\|\s*(?P<group2>[^{}]+))?
}{1,2}

and take group 1 or 2, respectively.


Broken down, this says:

{{1,2}                       # one or two {
(?P<group1>[^{}|]+)\s*       # capture anything not {}|
                             # into group 1
(?:\|\s*(?P<group2>[^{}]+))? # make the second group optional
}{1,2}                       # one or two }

You'll likely need to apply trim() to group1 to get rid off the possible trailing whitespaces.
See a demo on regex101.com.


A possible example in PHP that replaces the found examples could be:

<?php

$data = "**Nom de l'{{apprenti | apprentie}}** : {train_PrenomPersonne} {train_NomPersonne}";

$regex = '~
                {{1,2}
                (?P<group1>[^{}|]+)\s*
                (?:\|\s*(?P<group2>[^{}]+))?
                }{1,2}
                ~x';

$replacements = ['apprenti' => 'Chuck Norris', 'train_PrenomPersonne' => 'Jack', 'train_NomPersonne' => 'Jones'];

$data = preg_replace_callback($regex,

    function($match) use ($replacements) {
        $group1 = trim($match["group1"]);
        $group2 = (isset($match["group2"]))?$match["group2"]:"";

        // now do sth. with group1 and group2
        return (isset($replacements[$group1]))?$replacements[$group1]:$group1;
    },
    $data);

echo $data;
?>

Which in this case yields

**Nom de l'Chuck Norris** : Jack Jones

Upvotes: 2

Related Questions