www.webdeveloper.com
Results 1 to 7 of 7

Thread: regex help

  1. #1
    Join Date
    May 2005
    Posts
    242

    regex help

    Hello all,
    What I'm trying to accomplish is moving a user selected file to a user selected directory - if the selected file already exists in that directory I want to rename that file.

    For example: if user selects file 'abc.txt' i want to loop thru the selected directory and check for 'abc.txt'. If it exists copy and rename the file 'abc [1].txt' and if 'abc [1].txt' already exists name it 'abc [2].txt', etc.

    The code below works once until I get one duplicated copy 'abc [1].txt' after that it just overwrites that duplicated copy because I don't know how to check for the square brackets([x]).

    Code:
    function duplicate_file(file,dir) // file = 'abc.txt'
    {
      // split file name and extension
      var name = file.split('.');
    	
      // check for dupes in parent directory
      var str=name[0];
    
      // ?????????
      var patt = new RegExp('\\{'+str+'\\}', 'g');
    
      var dup_array = [];
      var d = dir.getDirectoryListing();
      var iterator = 1;
    
      for (var l=0;l<d.length;l++)
      {
        if(d[l].match(patt))
        {
          dup_array.push(d[l]);
          iterator++;
        }
      }	
      // put it all back together
      var dup = name[0] + ' [' + iterator + '].' + name[1];
      return dup;
    }
    Any ideas?? Thx!!!

  2. #2
    Join Date
    Aug 2009
    Posts
    593
    I don't know what your getDirectoryListing array looks like, so I haven't tested this, but this is essentially what I would do...

    Code:
    function duplicate_file(file, dir) // file = 'abc.txt'
    {
    	var
    		name  = file.split('.'),
    		part  = name[0],
    		list  = dir.getDirectoryListing(),
    		index = 0,
    		i;
    
    	do {
    		file = name.join('.');
    		for (i = 0; i < list.length; i++) {
    			if (list[i] == file) {
    				break;
    			}
    		}
    		name[0] = part + ' [' + index++ + ']';
    	} while(i < list.length);
    
    	return file;
    }
    Last edited by thraddash; 12-14-2010 at 01:51 AM.

  3. #3
    Join Date
    May 2005
    Posts
    242
    thanks thraddash, but that's not quite what i was needing. I've got the code figured out, just need help with the regex.

  4. #4
    Join Date
    Dec 2009
    Location
    Shropshire UK
    Posts
    153
    Just a start, and maybe something to work from.

    Code:
    var cache = ['abc[4].txt', 'xyz.txt', 'somethingElse[23].jpg']
    
    var reg = /^([^[\.]*)(?:\[(\d{1,3})\])?.(\w+)$/
    
    console.log (cache[0].match(reg)); //[1] = 'abc', [2] = '4', [3] = 'txt'
    console.log (cache[1].match(reg)); // [1] = 'xyz', [2] = undefined, [3] = 'txt'
    console.log (cache[2].match(reg)); // [1] = 'somethingElse', [2] = '23', [3] = 'jpg'

  5. #5
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Code:
    dir = ['abc.txt', 'abc[0].txt', 'abc[1].txt', 'xyz.txt', 'somethingElse[23].jpg'];
    file ='abc.txt';
    
    
    dc="*"+dir.join("*")+"*";
    
    while(dc.indexOf(file)!=-1){
     file=file.replace(/(\[\d+\])?\.(\w+)$/g,function(j,a,b){
     var n=a.slice(1,-1); 
     return "["+(  n!=""  ? parseInt(n)+1 : "0") +"]."+b;
     })
    }
    
    
    alert(file)

  6. #6
    Join Date
    Dec 2009
    Location
    Shropshire UK
    Posts
    153
    rnd me just racking my brains over your solution

    Two things that stood out was that I forgot to escape the . and \d+ is a bit more flexible.

    Had to look up slice(1,-1) as well i.e. 'defgh' becomes 'efg' or '[123]' becomes '123'.

    One quick question though. Is there any reason not to use this instead and miss out var n. Comes up with the same result in this test.

    Code:
    while(dc.indexOf(file)!=-1){
     file=file.replace(/(?:\[(\d+)\])?\.(\w+)$/g,function(j,a,b){
       return "["+(  a!=""  ? parseInt(a)+1 : "0") +"]."+b;
     })
    }
    Cheers

    edit: a breakdown of rnd me's code
    Code:
    var dir = ['abc.txt', 'abc[0].txt', 'abc[1].txt', 'xyz.txt', 'somethingElse[23].jpg'],
        file ='abc.txt',
        n = null;
    
    // *abc.txt*abc[0].txt*abc[1].txt* etc....
    var dc = "*"+dir.join("*")+"*";
    
    // while file matches somewhere in dc
    // note: file is ammended each iteration.
    // eg 1. abc.txt 2. abc[0].txt 3. abc[1].txt
    while( dc.indexOf(file)!=-1 ){
      file = file.replace(/(\[\d+\])?\.(\w+)$/g, function(j,a,b){
        
        // j is the overall match e.g. '.txt' then '[0].txt' etc .....
        // a = the match/capture in the first set of brackets (\[\d+\])? e.g '[0]' or '[1]' or optionally nothing ""
        // b = the match/capture in the second set of brackets (\w+) e.g. 'txt' or 'jpg'
     
        // slice (1,-1). Slice out string between the second and second to last character
        // e.g. 'abcdefg' becomes 'bcdef' or '[0]' becomes '0' or '[1]' becomes '1'
        n = a.slice(1,-1); 
    
        // replace j matched portion with '[n].b'
        // if n doesn't equal an empty string add 1 to the index
        // else set the index to 0
        return "["+(  (n!="")  
          ? parseInt(n)+1 
          : "0"
    	  ) +"]."+b;
      })
    }
    
    alert (dir[(dir.push(file))-1]); // abc[2].txt. push returns the length. that's a new one for me:)
    Last edited by rpg2009; 12-14-2010 at 05:56 PM.

  7. #7
    Join Date
    Dec 2009
    Location
    Shropshire UK
    Posts
    153
    Just tinkering

    Code:
    function addFile(dir, file){
      
      var mtch = null, 
          store = null,
          reg = /^([^[\.]*)(?:\[(\d+)\])?\.(\w+)$/,
          i = 0;
    	
      while ((mtch = reg.exec(dir[i++])) !== null) {
        if ( file === mtch[1] + '.' + mtch[3] ) store = mtch;
      }
    
      dir.push( (store)
        ? store[1] + '[' + ( store[2]
          ? parseInt(store[2]) + 1
          : '0' ) + '].' + store[3]
        : file
      );
      
      return dir;
      
    }
    PHP Code:
    var files = ['abc.txt''abc[0].txt''abc[1].txt''abc[2].txt''xyz.txt''somethingElse[23].jpg']

    console.log(addFile(files'abc.txt'));
    //["abc.txt", "abc[0].txt", "abc[1].txt", "abc[2].txt", "xyz.txt", 
    // "somethingElse[23].jpg", "abc[3].txt"]

    console.log(addFile(files'abc.txt'));
    //["abc.txt", "abc[0].txt", "abc[1].txt", "abc[2].txt", "xyz.txt", 
    // "somethingElse[23].jpg", "abc[3].txt", "abc[4].txt"] 
    Last edited by rpg2009; 12-14-2010 at 08:32 PM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles