A Flash Developer Resource Site

Results 1 to 4 of 4

Thread: Whitespace and regex

  1. #1
    Member
    Join Date
    Aug 2001
    Posts
    96

    Whitespace and regex

    Hi all,

    I have a text file that needs to be parsed correctly. The text file looks like this:

    PHP Code:
    [header]
       [
    header 2]
       [ 
    header3 
    I can grab these headers by doing so:

    var expression:RegExp = /[ [a-z0-9 ]+ ]/igxm;
    var items:Array = text.match(expression);


    But I would also like to remove the white space from before and after the brackets, so the headers can align against the left edge. Also, for [ header3 ], I would like to remove the white space inside the brackets, before "h" and after "3". What would be the correct regex for something this? Thanks in advance.

    tone
    Last edited by toneDigital; 02-04-2011 at 02:05 PM.

  2. #2
    Registered User nunomira's Avatar
    Join Date
    May 2002
    Location
    portugal
    Posts
    7,003
    Hi,

    Search for "[ " and " ]" and replace these whith "[" and "]" respectively?

  3. #3
    Member
    Join Date
    Aug 2001
    Posts
    96
    yes

  4. #4
    Senior Member
    Join Date
    Jul 2008
    Posts
    391
    I think you need 2 RegExps to do this, this is what I came up with
    PHP Code:
    var s:String //Assume s holds the contents of the entire text file
    s.replace (/\s*\[\s*/g"[");
    s.replace (/\s*\]\s*/g"]"); 
    If you don't understand the expressions I'll break it down.
    \s is a metasequence that matches any whitespace - space, carriage returns, line feeds, etc
    * means match the previous item zero or more times
    \[ means match "[", you need the slash because [ is a metacharacter
    g means match this expression through the entire string

    So the first expression says match all white spaces before and after every "[" and replace them with just "[". Second is the same thing but with "]".

    This results in
    PHP Code:
    [header][header 2][header3
    So you can split this string into an array using [ or ] as the delimiter.

    PS: I love expressions, I think they're so cool.

Posting Permissions

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




Click Here to Expand Forum to Full Width

HTML5 Development Center