How I can match the following files name using regex.
index.js
[id].js
[...params].js
I tried this regex on my own but it seems to be not work
[a-z[]*.tsx
index.js // working
[id].js // not working
[...params].js // not working
If I understand correctly you want to validate JavaScript file names that have alphanumeric characters, and are optionally enclosed in [
...]
or [...
...]
. Based on this you can use this regex, here with a number of tests:
[ 'index.js',
'[id].js',
'[foo].js',
'[...params].js',
'[..invalid1].js',
'[invalid2.js',
'#invalid3.js',
'invalid^4.js',
'invalid[5].js',
'[(invalid)6].js',
'invalid7.css',
].forEach(name => {
let isValid = /^(?:[a-zA-Z0-9]+|\[(?:\.{3})?[a-zA-Z0-9]+\])\.js$/.test(name);
console.log(name, '=>', isValid);
});
Output:
index.js => true
[id].js => true
[foo].js => true
[...params].js => true
[..invalid1].js => false
[invalid2.js => false
#invalid3.js => false
invalid^4.js => false
invalid[5].js => false
[(invalid)6].js => false
invalid7.css => false
Explanation of regex:
^
-- anchor pattern at start of string(?:
-- start of non-capture group (for logical or
)
[a-zA-Z0-9]+
-- 1+ alphanumeric chars|
-- logical or
\[
-- literal [
(?:\.{3})?
-- optional 3 dots[a-zA-Z0-9]+
-- 1+ alphanumeric chars\]
-- literal ]
)
-- end of non-capture group\.js
-- literal .js
$
-- anchor pattern at end of stringTo learn more about regex language: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex