views:

48

answers:

2

Hi Guys,

I need a regular expression to capture field names listed in a string. They are listed between Here are my requirements:

  1. field names in curly braces
  2. field names have no spaces
  3. curly braces can be escaped with a \

So in the following:

capture {this} text and exclude \{that}?

The matches are {this} but not {that}.

I'm using PHP and preg_match (i could use a diff function, i'm open to ideas)

Any ideas? care to explain the result as well for me so I might learn something :)

+1  A: 

You can use a negative lookbehind: (?<!\\)\{[^}]+\}. (Remember to escape the \ for PHP)

The expression (?<!something) is a zero-width assertion that will only allow the subsequent expression to match text that isn't preceded by something.
Thus, this regex matches \{[^}]+\} only if it's not preceded by \\. (The \ must be escaped)

SLaks
1. you've lost one \ 2. you've lost quantifier for ^}
zerkms
@zerkms: 1. Huh? I'm not showing a PHP string. 2. Fixed; thanks.
SLaks
+1  A: 
$s = 'capture {this} text and exclude \{that} {a} \{b} {c}?';
preg_match_all('~(?<!\\\){[^}]+}~', $s, $matches);
var_dump($matches);

In details you can read about negative assertion (?<! here

zerkms