www.webdeveloper.com
Results 1 to 5 of 5

Thread: RegEx to count lines in a file

  1. #1
    Join Date
    Aug 2005
    Posts
    243

    RegEx to count lines in a file

    I'm using jQuery to pull a file asynchronously. I want to then sum the total of lines in that file that begin with "/". The file is a cache manifest and looks something like this...

    /path/to/file.jpg
    /path/to/another/file.css

    etc.

    Is there a simple approach to this? I've been messing with regex to get it done and not having much luck...
    Current Client - http://bodylabfitness.com

  2. #2
    Join Date
    Dec 2010
    Location
    Hudson Valley, NY
    Posts
    16

    Regex starting with "/"

    You have either a simple or a non-trivial problem. I'll assume it's the former, you can get back if it's the latter.

    / - start of regex
    ^ - start of input
    / - end of input, so, escape it:
    \/
    . - any character
    * repeated any number of times
    $ - end of input
    / - end of regex

    so:
    var count = 0;
    for ( var line in file ) {
    if ( line.match( /^\/.*/ ) ) { count += 1; }
    }

  3. #3
    Join Date
    Dec 2010
    Posts
    207
    Something like this perhaps:
    Code:
    function count( str, re )
    {
       var m = str.match( re );
    
       return m ? m.length : 0;
    }
    
    alert( count( myString, /(^|\r*\n)\//g ) );


    Q: I found this code...
    A: Then find its author.

  4. #4
    Join Date
    Dec 2010
    Location
    Hudson Valley, NY
    Posts
    16

    Line counting

    That RE assumes your whole file is in a single string.

    It uses the "g" suffix to match globally: /regex here/g

    That regex finds either A or B where A is the start of the input and B is (zero or more returns, followed by a single newline) followed by the forward slash character.

    Very slick. I will definitely use those thoughts.

  5. #5
    Join Date
    Aug 2005
    Posts
    243
    great stuff, thanks to you both!
    Current Client - http://bodylabfitness.com

Thread Information

Users Browsing this Thread

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

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