0

I'm new to working with regular expressions and was wondering if the following regex could somehow be simplified...

{{(?:[\s]+)?(.*)([\s]+)?}}

I am trying to get the string out of the following pattern...

{{SOME_STRING}}
{{    SOME_STRING}}
{{  SOME_STRING   }}
{{  SOME-STRING      }}
{{  SomE STRING  }}

Additionally, it doesn't quite work right as there should not be any trailing spaces on the match.

Regex101 Link: http://regex101.com/r/kT9yT5

user1960364
  • 1,951
  • 6
  • 28
  • 47

3 Answers3

1

there should not be any trailing spaces on the match

You can try below regex and get the matched group

/{{\s*(.*?)\s*}}/g

that means every thing that is enclosed inside {{ and }} are grouped using Reluctant quantifiers.

Here is Online Demo

Read more about Greedy vs. Reluctant vs. Possessive Quantifiers

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
1

For A Direct Match, use \K Magic

{{\s*\K[^}]+?(?=\s*}})

See demo.

Explanation

  • {{\s* matches the opening braces and any whitespace characters
  • The \K tells the engine to drop what was matched so far from the final match it returns
  • The negated character class [^}]+? lazily matches any characters up to...
  • The point where the lookahead (?=\s*}}) can assert that what follows is spaces and the closing braces.

Sample Code

See the output at the bottom of the live php demo.

$regex = '~{{\s*\K[^}]+?(?=\s*}})~';
preg_match_all($regex, $yourstring, $matches);
print_r($matches[0]);

Output

[0] => SOME_STRING
[1] => SOME_STRING
[2] => SOME_STRING
[3] => SOME-STRING
[4] => SomE STRING
zx81
  • 41,100
  • 9
  • 89
  • 105
0

You could try the below regex to remove all the trailing and beginning white spaces present inside the {},

\{\{\s*(\w+[-\s]?\w+)\s*\}\}

DEMO

Explanation:

  • \{\{ Literal opening curly braces {{
  • \s* zero or more spaces.
  • \w+ One or more word characters.
  • [-\s]? Optional - or space character.
  • \w+ One or more word characters.
  • \s* Zero or more space characters.
  • \}\} Literal closing curly braces }}

You code would be,

$regex = '~\{\{\s*(\w+[-\s]?\w+)\s*\}\}~';
preg_match_all($regex, $yourstring, $matches);
print_r($matches[1]);

Ideone

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274