Skip to content
Advertisement

Need assistance with regular expression [closed]

I have many strings enclosed within a function called trans. In some places it could be trans(‘Hello’) or trans(“Hello”) I want to write a regular expression that returns only Hello in both cases.

JavaScript

This is what I came up with but it doesn’t work in my code. Returns other strings as well with single or double quotes. I am using the above in a preg_match_all function as I have to had to escape the single quotes in my regex.

I could also have a string like this within the trans function “It’s never happened”

Advertisement

Answer

You need to keep a copy of the opening quotation mark and use it to match the closing quotation mark at the end of the matched string. If back-references worked inside character classes, you could do that with an expression like /trans((['"])([^1]*)1)/, but instead you have to use a negative lookahead — replace [^1]* with ((?!1).)*.

Try this:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement