DissociatedFun
DissociatedFun

Reputation: 51

Regex Expression for words between two punctuation

How can I make this regex expression find every string in my text that matches this format, I tried adding the curly braces but it only find the first word in the format and when removed it find every word.

My regex expression: {((?:[a-z][a-z0-9_]*))
My text: {Hello|Hi|Hey} John, How are you? I'm fine

Upvotes: 2

Views: 499

Answers (2)

The fourth bird
The fourth bird

Reputation: 163352

To get all the matches between curly brackets, you could match from { till } and capture what is in between in a capturing group.

Then use explode and use | as a delimiter. If you have multiple results you could loop the results:

$str = "My text: {Hello|Hi|Hey} John, How are you? I'm fine";
preg_match_all('~{([^}]+)}~', $str, $matches);

foreach($matches[1] as $match) {
    print_r(explode('|', $match));
}

Result

Array
(
    [0] => Hello
    [1] => Hi
    [2] => Hey
)

Php demo

Another option could be to make use of the \G anchor:

(?:\G(?!\A)|{(?=[^{}]*?}))([^|{}]+)[|}]

Explanation

  • (?: Non capturing group
    • \G(?!\A) End of the previous match but not at the start
    • | Or
    • {(?=[^{}]*?}) Match { and assert what follows contains not } and then }
  • ) Close non capturing group
  • ([^|{}]+) Capture in a group matching NOT what is listed in the character class
  • [|}] Match what is listed in the character class

php demo

Upvotes: 1

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use this look around based regex that will give you all the matches in curly brackets,

(?<=[{|])\w+(?=[|}])

Demo

Try this Python code,

$s = "{Hello|Hi|Hey} John, How are you? I'm fine";
preg_match_all('/(?<=[{|])\w+(?=[|}])/',$s,$matches);
print_r($matches);

Array
(
    [0] => Array
        (
            [0] => Hello
            [1] => Hi
            [2] => Hey
        )

)

Online PHP demo

Upvotes: 1

Related Questions