How to use '\' in Python lookbehind assertion regex (? <= \\) to match strings quoted from C ++

How can I match r '\ a' in Python using the lookbehind statement?
In fact, I need to map C ++ strings like "a \" b"and

"str begin \
end"

I tried:

>>> res = re.compile('(?<=\)a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 244, in _compile
    raise error, v # invalid expression

>>> res = re.compile('(?<=\\)a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 244, in _compile
    raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis

>>> res = re.compile('(?<=\\\)a')
>>> ms = res.match(r'\a')
>>> ms is None
True

Real-
world example: When I parcing "my s\"tr"; 5;, like ms = res.match(r'"my s\"tr"; 5;'), the expected result:"my s\"tr"

Answer
Finally, stribizhev provided a solution. I thought my initial regex was less computationally expensive and the only problem was that it should be declared using an unprocessed string:

>>> res = re.compile(r'"([^\n"]|(?<=\\)["\n])*"', re.UNICODE)
>>> ms = res.match(r'"my s\"tr"; 5;')
>>> print ms.group()
"my s\"tr"
+4
4

EDIT. , Word Aligned

, :

(?s)"(?:[^"\\]|\\.)*"

. regex101.

Python ( TutorialsPoint):

import re
p = re.compile(ur'(?s)"(?:[^"\\]|\\.)*"')
ms = p.match('"my s\\"tr"; 5;')
print ms.group(0)
+1

, , C ++ :

(?s)"(?:[^"\\\n]|\\.)*"

, , , , [^"\\\n], [^"\\] .

:

"a \" b"

"a \
 b"

"\\"

"\\\
kjsh\a\b\tdfkj\"\\\\\\"

"kjsdhfksd f\\\\"

"kjsdhfksd f\\\""

regex101

stribizhev (?s)((?<!\\)".+?(?<!(?<!\\)\\)") "kjsdhfksd f\\\"", \.

\ , , split tokenize CSV .

+2

, , "" :

(?s)"[^"\\]*(?:\\.[^"\\]*)*"

, lookbehind.

nhahtdh, /, , \n :

(?s)"[^"\\\n]*(?:\\.[^"\\\n]*)*"
+1

\ escape-, \\ ( ) , python \a hex:

>>> '\a'
'\x07'

re.search, re.match mchecks :

>>> re.search(r'(?<=\\)a','\\a')
<_sre.SRE_Match object at 0x7fb704dd0370>
>>> re.search(r'(?<=\\)a','\\a').group(0)
'a'

, :

>>> re.search(r'"(.*)"','"my s\"tr"; 5;').group(0)
'"my s"tr"'
0

All Articles