Match a string literal via regex

You are right. I think what’s tripping you up is more likely than not what I linked above: behaviour for quotes following slashes inside raw strings. Specifically, you have \\" inside your character class, and that’s interpreted differently in Julia than elsewhere.

Here’s the easiest way I found to get it to work. I tried to make it extra readable by using the x modifier, which allows whitespace and comments as follows:

julia> str = repr("xxxxxxxxxx\"xxxxxxxxxxxxxx\"");

julia> regex = r"""
       \G     # match start
       \"     # opening quote
       (?:    # don't capture (better performance)
           [^\"\\]+  # not a quote or a slash
           |         # or
           \\.       # an escaped character
       )*?    # ungreedy multiples of the above
       \"     # closing quote
       """x;

julia> match(regex, str)
RegexMatch("\"xxxxxxxxxx\\\"xxxxxxxxxxxxxx\\\"\"", 1="\\\"")

Hope that helps!

5 Likes