简体   繁体   中英

Find file sequence with RegExp in Javascript

I have a simple question:

How do I use RegExp in Javascript to find strings that matches this filter: *[0-9].png in order to filter out file sequences.

For example:

bird001.png
bird002.png
bird003.png

or

abc_1.png
abc_2.png

Should ignore strings like abc_1b.png and abc_abc.png I'm going to use it in a getFiles function.

var regExp = new RegExp(???);
var files = dir.getFiles(regExp);

Thanks in advance!

EDIT:

If I have a defined string, let's say

var beginningStr = "bird";

How can I check if a string matches the filter

beginningStr[0-9].png

? And ideally beginningString without case sensitivity. So that the filter would allow Bird01 and bird02.

Thanks again!

If I understood correctly, you need a regex that matches files with names which:

  1. Begin with letters az , AZ
  2. Optionally followed with single _
  3. Followed by one or more digits
  4. Ending with .png

Regex for this is [a-zA-Z]_{0,1}+\\d+\\.png

You could try online regex builders which offer immediate explanation of what you write.

Anything followed by [0-9] and ened by .png :

/^.*[0-9]\.png$/i

Or simply without begining (regex will find it itself):

/[0-9]\.png$/i

If I understood correctly,

var re = /\s[a-zA-Z]*[0-9]+\.png/g;
var filesArr = str.match(re);
filesArr.sort();// you can use own sort function

Please specify what is the dir variable

To get the PNG files without the sequenced? In one statement:

var files = dir.getFiles(/.*[^\d]+\.png$/i);

[^\\d]+ matches the non-number characters.

To only get the sequenced:

var files = dir.getFiles(/.*\d+\.png$/i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM