Create a regex to extract a string that contain a noral character and escaped string without DOS

I have a string like this:

///////AB?\a\b\c\d\d\e\\f\a\a\b\cd\ed\fmnopqrstuvwxy\z\a\a\a\a\a\a\a\a\a///imgy

it started with /// and ended with ///imgy (i and/or m and/or g and/or y), and between the beginning and end are the character are normal character like a or escaped character like \a.

Here is my regex:

/^\/{3}((?:\\?[\s\S])+?)\/{3}([imgy]{0,4})(?!\w)/

But the problem is that it is reported as "vulnerable to denial-of-service attacks". The main part that has the problem is

(?:\\?[\s\S])+

How can I create a right one that can figure out both a and \a? Thank you!

20 thoughts on “Create a regex to extract a string that contain a noral character and escaped string without DOS”

  1. You might list the characters that are allowed to a character class, and optionally repeat an escaped character [a-z]

    ^\/{3,}[A-Za-z?]+(?:\\[a-z\\][A-Za-z?]*)*\/\/\/[imgy]{0,4}$
    

    The pattern matches:

    • ^ Start of string
    • \/{3,}[A-Za-z?]+ Match 3 or more / and 1 or more times any of the listed allowed chars
    • (?: Non capture group
      • \\[a-z\\] Match an escaped char a-z or \\
      • [A-Za-z?]* Optionally match any of the listed
    • )* Close an optionally repeat the group
    • \/\/\/[imgy]{0,4} Match /// and 0-4 times any of i m g or y If there should be at least a single char, you can use {1,4}
    • $ End of string

    Regex demo

    Reply

Leave a Comment