3

what is wrong with my preg_match ?

preg_match('numVar("XYZ-(.*)");',$var,$results);

I want to get all the CONTENT from here:

numVar("XYZ-CONTENT");

Thank you for any help!

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71

4 Answers4

2

I assume this is PHP? If so there are three problems with your code.

  1. PHP's PCRE functions require that regular expressions be formatted with a delimiter. The usual delimiter is /, but you can use any matching pair you want.
  2. You did not escape your parentheses in your regular expression, so you're not matching a ( character but creating a RE group.
  3. You should use non-greedy matching in your RE. Otherwise a string like numVar("XYZ-CONTENT1");numVar("XYZ-CONTENT2"); will match both, and your "content" group will be CONTENT1");numVar("XYZ-CONTENT2.

Try this:

$var = 'numVar("XYZ-CONTENT");';
preg_match('/numVar\("XYZ-(.*?)"\);/',$var,$results);

var_dump($results);
Francis Avila
  • 31,233
  • 6
  • 58
  • 96
1

Paste your example string into http://txt2re.com and look at the PHP result.

It will show that you need to escape characters that have special meaning to the regex engine (such as the parentheses).

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
0

You should escape some chars:

preg_match('numVar\("XYZ-(.*)"\);',$var,$results);
0xd
  • 1,891
  • 12
  • 18
  • Sorry, it doesn't work, I get: Delimiter must not be alphanumeric or backslash –  Nov 25 '11 at 22:09
  • Actually you have to escape even more chars, namely the backslashes themselves. Also the pattern itself is missing start/end delimiters, e.g. `/` – Dominik Honnef Nov 25 '11 at 22:13
  • Ok, but when I add `/` on the beginning & end it returns no results –  Nov 25 '11 at 22:18
0
preg_match("/XYZ\-(.+)\b/", $string, $result);
print_r($result[0]); // full matches ie XYZ-CONTENT
print_r($result[1]); // matches in the first paren set (.*)
skibulk
  • 3,088
  • 1
  • 34
  • 42