www.webdeveloper.com
Results 1 to 7 of 7

Thread: regex help

Hybrid View

  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 02: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)
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

  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 06: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 09: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

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.13160 seconds
  • Memory Usage 3,094KB
  • Queries Executed 13 (?)
More Information
Template Usage (31):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (7)bbcode_code
  • (1)bbcode_php
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (7)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (7)postbit
  • (7)postbit_onlinestatus
  • (7)postbit_wrapper
  • (1)showthread_list
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (27):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./includes/functions_threadedmode.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (72):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids_threaded
  • showthread_threaded_construct_link
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates