Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
Regular Expressions If Else

I have a string: /foo/{bar}/{baz?}

Now i want to extract all words inside the {...}. But on the word with the "?" i want to select not only the {...} but also the "/" before "{"

So far i got this:

$string = '/foo/{bar}/{baz?}';

preg_match_all('~{(\w+)[?]?}~', $string, $matches);
print_r($matches);

Result:

Array
(
    [0] => Array
        (
            [0] => {bar}
            [1] => {baz?}
        )

    [1] => Array
        (
            [0] => bar
            [1] => baz
        )

)

But should be:

Array
(
    [0] => Array
        (
            [0] => {bar}
            [1] => /{baz?}
        )

    [1] => Array
        (
            [0] => bar
            [1] => baz
        )

)

(Notice the / before the {baz?} match)

Hope this is clear enough my english is not so good. Thanks

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Use a branch reset group ((?|...|...)) with 2 capturing groups inside that will share the same ID:

/(?|\/{(\w+)\?}|{(\w+)})/

See the regex demo

Details:

  • (?| - branch reset group start
  • \/{(\w+)\?} - a /{, then 1+ word chars (captured into Group 1) and then ?}
  • | - or
  • {(\w+)}) - a { followed with 1+ word chars (captured into Group 1 again) and then }.

PHP demo:

$re = '/(?|\/{(\w+)\?}|{(\w+)})/';
$str = '/foo/{bar}/{baz?}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
print_r($matches);
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda