Home > Enterprise >  Match java-script files name using regex
Match java-script files name using regex

Time:12-15

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 not working

[a-z[]*.tsx


index.js // working
[id].js // not working
[...params].js // not working

CodePudding user response:

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 string

To learn more about regex language: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex

CodePudding user response:

To match the above file names using regex, the pattern can be:

^[a-zA-Z][a-zA-Z0-9]*\.js$

This pattern will match file names that start with any alphabet and contain only alphabets and numbers. It will also ensure that the file name ends with .js.

For example, the following file names will be matched by this pattern:

index.js
abc123.js
fileName123.js
sample123.js

But the following file names will not be matched:

index.txt
abc123.png
file Name123.js
sample_123.js

Note: The pattern [...] in the file name is not matched by the above regex pattern as it contains special characters that need to be escaped. To match such file names, the pattern can be modified as follows:

^[a-zA-Z][a-zA-Z0-9]*(\[\.\.\.\w \])?\.js$

This pattern will match file names that may or may not contain the [...] pattern in the middle. The [...] pattern will only be matched if it is present in the file name and is surrounded by square brackets.

  • Related