I take the answer of @gurvinder372 and try to explain it for better understanding
/[\w-]+.(jpg|png|txt)/g
To explain what does the regex do :
/
: Delimiter, denoting the beginning and the end of the regex
[\w-]
: the brackets [
and ]
enclose the ad hoc definition of a set of characters. In this case, the set firstly should include all the characters of the predefined character set \w
, defined to be all alphanumeric characters and the underscore; additionally, the character set should contain the hyphen -
which does not belong to the predefined character set \w
+
: is one of several possible quantifiers following the definition of a character set, it says: "at least one occurrence of elements of the specified character set" (other quantifiers are *
= 0, 1, or any more occurrences, ?
= 0 or 1 occurrences, and {n,m}
= at least n, at most m occurrences.
.
: the dot means an arbitrary ("any") character. What was really meant here was \.
, the character .
. The "any" specifier works by chance here, since the dot is a character!
(jpg|png|txt)
: alternation: following the .
arbitrary character, there should occur either one of the character sequences separated by the vertical bar.
/g
: after the delimiter /
finishing the regular expression, several modifiers are possible. The modifier g
here instructs functions like match()
to look for as many subsequences of the string as possible that match the regex. If it would be ommitted, the regex engine would stop searching after having found the first match of the pattern. Actually, this would be completely sufficient in this case, as the URL is supposed to contain only one filename, so it can stop after having found the match.