Hello! I have a regex `[^\\]\\\"` but I can't seem...
# getting-started
s
Hello! I have a regex
[^\\]\\\"
but I can't seem to make it compile and used from a Regex class - what am I missing? attached is an IntelliJ screenshot. I honestly tried all possible escapings. IDE and compiler complain about "redundant escape character". The regex as typed in this question is 100% correct and fully tested
j
First, I would suggest using raw strings (triple-double-quoted) so you don't have to think about 2 levels of
\
escaping
same 1
1
And I guess that is your problem here, you seem to only escape at Regex level, but you didn't escape your backslashes for the string literal. Adding 2 double-quotes on each side should solve it
s
Alternatively, the IDE can help you out: • make a string • choose “Inject language or reference” from the quick actions menu • Select “regular expression” • Select “edit RegExp” fragment from the quick actions menu • Now you can paste the regex in directly to the regular expression editor and IntelliJ will escape it for you
s
Yes I believe you are correct,
"""
works but now still some escaping hell with the slashes, I'll figure it out from here, thanks!
s
The warning about the redundant escaping is valid,
"
does not need to be escaped in a regular expression (although it does in a Kotlin string)
s
🙏
j
So in short
Regex("""[^\\]\\"""")
should work (it's a bit hard to digest that there are 4 double-quotes at the end (1 for your regex, and 3 for the closing raw string 😆)
m
Out of curiosity, what is this regex trying to find; "not-a-backslash followed by a backslash followed by a double quote"?
j
and then a double-quote, yes. I guess the point is to find escaped double-quotes in some text, but making sure the backslash that escapes the double-quote is not itself escaped
m
<nod> tks. Didn't mean to necro the thread, but was curious
j
It's only 3 days old 🙂 but also I don't see a problem in reviving old threads
👍 1