Hello, I have a regex made to match markdown links...
# javascript
l
Hello, I have a regex made to match markdown links that works perfectly in Kotlin/JVM, but in JavaScript, it leads to a runtime error:
Copy code
SyntaxError: Invalid regular expression: /\[(?<text>.+)\]\((?<url>[^) ]+)(?: \"(?<title>.+)\")?\)/: Invalid escape
    at new RegExp (<anonymous>)
Here's the source code that works in the JVM and fails in Chrome :
Copy code
//language=RegExp
val linksRegex = """\[(?<text>.+)\]\((?<url>[^) ]+)(?: \"(?<title>.+)\")?\)""".toRegex()
When I look at the generated JavaScript code, here's what I get:
Copy code
var tmp0_toRegex_0 = '\\[(?<text>.+)\\]\\((?<url>[^) ]+)(?: \\"(?<title>.+)\\")?\\)';
I tried to workaround using
js("…")
:
Copy code
val linksRegex = js("""'\[(?<text>.+)]\((?<url>[^) ]+)(?: "(?<title>.+)")?\)'""").unsafeCast<String>().toRegex()
Unfortunately, it then seems to strip the backslashes away as it's matching quite random strings that are not markdown-style links at all but plain English sentences. Is there a way to get that Regex to work in JS like it does in the JVM?
e
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions JS RegExp is a different language than Java Pattern, and Kotlin's Regex just delegates to the platform
in this case though, I don't see why you're trying to escape
"
, it's not a special character
👍🏼 1
r
This should work fine on both JVM and JS:
"""\[(?<text>.+)\]\((?<url>[^) ]+)(?: "(?<title>.+)")?\)"""
👍 1
👍🏼 1
l
Thank you very much for the help, the escapes of the double quotes were the culprit as you found, and I didn't notice because the unneeded escapes were ignored on the JVM.
287 Views