2

I'm trying to match 4 backslahes using preg_match.

preg_match('/\\\\\\\\/',$subject) works fine, but preg_match('/\\{4}/',$subject) doesn't.

Perhaps I'm using {} incorrectly. Could anyone advise?

dewd
  • 4,380
  • 3
  • 29
  • 43
  • 1
    Hmm it works fine for me, http://regexr.com/391nd – Déjà vu Jun 23 '14 at 08:46
  • stange. i'm getting 0 rtned in php. maybe its a php thing? – dewd Jun 23 '14 at 08:50
  • You are right, in php it is not working. Somehow the second backslash escapes the `{` – colburton Jun 23 '14 at 08:53
  • You need 4 backslashes to match 1 backslash. I explained this in a previous [answer](http://stackoverflow.com/a/18017821) – HamZa Jun 23 '14 at 09:13
  • 1
    @HamZa I always fear getting caught out by the dupe police, no matter how thoroughly I search - both google and stackoverflow search engines. And there you are... right on queue! ;) good answer to link to though, so thanks! – dewd Jun 23 '14 at 09:31

3 Answers3

2

Ok I got it: Two backslashes mean you want one backslash in your string: So for the regex it looks like this: /\{4}/ Which means you want to escape the {

What you need here is:

preg_match('/\\\\{4}/', $subject);

That looks for the regex like this: /\\{4}/ and works properly.

colburton
  • 4,685
  • 2
  • 26
  • 39
1

Use this:

preg_match('/(?:\\\\){2}/',$subject, $m);

It matches 4 backslashes.

Toto
  • 89,455
  • 62
  • 89
  • 125
  • thx M42. I haven't tested it yet, but I don't doubt you (I will test it shortly). Are you able to explain why a non-capturing group is needed in this context please? – dewd Jun 23 '14 at 09:05
  • @dewd: Not sure :) but without grouping the quantifier `{4}` affect only the second backslash, so the expression is like `\\\\\` that is like a single `\` that escape the `{` and then no match. – Toto Jun 23 '14 at 09:09
  • This reads for the regex like this `/(?:\){4}/` since there is no such thing as `\)`, there is no escaping taking place, and the backslash is taken literally. – colburton Jun 23 '14 at 09:19
  • this seems to be returning false - as in error. have you tested it? – dewd Jun 23 '14 at 09:24
1

Regex is the wrong tool when you're looking for a literal string.

strpos($subject, str_repeat("\\",4)) !== false
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • true, and good point, but i'm not just looking for a literal string. to keep it simple, i've just given you the part of the regex that's failing. you don't need the rest of it. – dewd Jun 23 '14 at 09:09