How do I match double backslash in a single-quoted string?

perl, regex

Solution

In Perl, single quoted strings have just two backslash escapes:

- The delimiter, e.g. `'John\'s car'`.

- The backslash. This is neccessary when we want a trailing backslash: `'foo\bar\\'`

All other backslashes are literal. The unfortunate consequence of this is, that for n actual backslashes, either 2n-1 or 2n backslashes must be used in your single quoted string literal.

Regexes have the same backslash semantics as double quoted strings.

You already have a regex that matches a leading double backslash: `/^\\\\/`. This obviously won't match a single leading backslash.

If you want to match a single backslash, and a single backslash only, just make sure that the first backslash is not followed by another one. This uses a negative lookahead: `/^\\(?!\\)/`.

Problem

I need to distinguish between string with single and double backslashes. Perl treats them equally: ``` print "\n" . '\qqq\www\eee\rrr'; print "\n" . '\\qqq\www\eee\rrr'; ``` will give the same result: ``` \qqq\www\eee\rrr \qqq\www\eee\rrr ``` Even more, the next calls: ``` print "\n" . leadingBackSlash('\qqq\www\eee\rrr'); print "\n" . leadingBackSlash('\\qqq\www\eee\rrr'); print "\n" . leadingBackSlash('\\\qqq\www\eee\rrr'); print "\n" . leadingBackSlash('\\\\qqq\www\eee\rrr'); ``` to function : ``` sub leadingBackSlash { $_ = shift; print "\n$_"; print "\n" . length($_); if( m/^\\\\/) { print "\ndouble backslash is matched"; } if( m/^\\/) { print "\nsingle backslash is matched"; } } ``` will produce result : ``` \qqq\www\eee\rrr 16 single backslash is matched \qqq\www\eee\rrr 16 single backslash is matched \\qqq\www\eee\rrr 17 double backslash is matched single backslash is matched \\qqq\www\eee\rrr 17 double backslash is matched single backslash is matched ``` i.e. it matches double backslash as single one. Could you please help me with regexp to match double but not single backslash?

Original source