Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Mar 2005
    Location
    France, Bordeaux
    Posts
    44
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question RegExp match extraction

    I have a string containing an pseudo-array serialized in that form '@key1:value1@key2:value2'

    I want to extract all keys but I can't get rid of the opening '@' and trailing ':' out of each key...

    Is there some wise developper able to point out the ugly mistake in my code:
    Code:
    var text = "@key1:value1@key2:value2";
    var keys = text.match(new RegExp("@([^@:]*):", 'g');
    Thanks in advance.

    PS: as a workaround, I sliced(1, -1) the keys, but I'm looking for a more general solution...
    Last edited by MyttO; 04-12-2005 at 03:57 PM.

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    UmeŚ, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    If you're doing a global search you will be using the entire match and not just the captured part of it. There's no easy way of getting rid of the '@', but the easy way of making sure the ':' is not included is to write a regex that does not match ':' at the end, like this /@[^:]+/g.


    Regex functionality can be tricked into doing lots of stuff if you want something more than a list of keys, though. Look at this, for example:
    Code:
    function buildObject(m,p1,p2){
        oList[p1]=p2;
        return'';
    }
    
    var
        reTuple=/@([^:]+):([^@]+)/g,
        sTest='@a:A@b:B@c:C',
        oList={};
    
    sTest.replace(reTuple,buildObject);
    alert([oList['a'],oList['b'],oList['c']]);
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #3
    New Coder
    Join Date
    Mar 2005
    Location
    France, Bordeaux
    Posts
    44
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thumbs up Very very interesting

    Indeed, this is very interesting and you had the right guess on my intentions

    In fact I obviously want to build an collection, as an array in my case. By the way, why would I prefer an object as you do? I'm pretty new to JSing, and I've seen that many times, but couldn't figure out why by myself.

    Another question: it looks like there's an unused 'm' parameter in the callback sent to replace (I didn't know this was possible). Is it the typical mandatory prototype for the function?

    Anyway, thanks a lot for your help


  •  

    Posting Permissions

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