Reputation: 51
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
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
)
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 classUpvotes: 1
Reputation: 18357
You can use this look around based regex that will give you all the matches in curly brackets,
(?<=[{|])\w+(?=[|}])
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
)
)
Upvotes: 1