www.webdeveloper.com
Results 1 to 4 of 4

Thread: capture each item in comma seperated list with reg ex?

Hybrid View

  1. #1
    Join Date
    Oct 2007
    Posts
    94

    capture each item in comma seperated list with reg ex?

    I have a comma separated list, the curve ball is, some of the items are strings with commas inside them (so I cant just exploid the string using a comma as a separator). How can I write a reg to capture the 10 items?

    list might be like this

    "item 1", 2, 4545, "fgdfg", 435345, "10,000", "asdasd", "some other string, ok?"

    In other words, each item is separated by a comma, but some items are string (double quotes) that contain comma themselves.

  2. #2
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    782
    I would normally have done this using a function instead of a regular expression, but here is my attempt anyway :P

    Code:
    <script type="text/javascript">
    
    	document.write('"item 1", 2, 4545, "fgdfg", 435345, "10,000", "asdasd", "some other string, ok?"'.split(/,\x20(?=\x22|\d)/).join('<br />'));
    
    </script>
    Output:
    Code:
    "item 1"
    2
    4545
    "fgdfg"
    435345
    "10,000"
    "asdasd"
    "some other string, ok?"
    I know it's not foolproof but it worked on your example string, hopefully gives some ideas.
    JavaScript: Learn | Validate | Compact

  3. #3
    Join Date
    Nov 2010
    Posts
    66
    looks good, but there are two other curve balls I forgot to mention

    The list may not have spaces between them and it may not have anything, so for example:
    "item 1",,,"aaab","bbbc", "cccd"

    Id need to know [2] and [3] are empty while [1], [4], [5], [6] have data...

    Im not very good with regex, think ill give up on them and write a function for this instead... I was originally started writing some sort of regex that looks for either a string, a number or nothing, and copy/paste this for each element (so I can access it in the array)

  4. #4
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    782
    Yeah, honestly a function could handle a lot more "features" in my opinion.
    For example, you might have had a string with an escaped quote inside it as well:

    "Normal String", "String, with comma", "String with \"Quotes\"!",1,2,3
    JavaScript: Learn | Validate | Compact

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