a simple command that splits up a string into numbers and letters

Discussion in 'Ruby' started by shawn bright, Feb 5, 2009.

  1. shawn bright

    shawn bright Guest

    [Note: parts of this message were removed to make it a legal post.]

    Hey all,

    i am looking for an easy way to split a string into letters and numbers.
    so if i had a string '34JKBY103' i could get ['34', 'JKBY', '103']

    I could write up something, but thought that if there was already something
    out there that i hav'nt found, it would probably be cleaner.
    thanks

    sk
     
    shawn bright, Feb 5, 2009
    #1
    1. Advertisements



  2. irb> '34JKBY103'.scan(/\d+|\D+/)
    => ["34", "JKBY", "103"]

    that looks like an easy way ;-)

    -Rob

    Rob Biedenharn http://agileconsultingllc.com
     
    Rob Biedenharn, Feb 5, 2009
    #2
    1. Advertisements

  3. shawn bright

    Tim Greer Guest

    I don't know if there's anything out there now (there might be), but it
    seems pretty simple. Just split on either \d+ or \D+, depending
    (unless I'm missing something in your requirement)?
     
    Tim Greer, Feb 5, 2009
    #3
  4. shawn bright

    shawn bright Guest

    [Note: parts of this message were removed to make it a legal post.]

    sorry, how do i split on a \d+ ?
    sk

     
    shawn bright, Feb 5, 2009
    #4
  5. shawn bright

    Tim Greer Guest

    <please don't quote signatures>

    Someone posted this already, but:

    irb(main):010:0> s = "34JKBY103"
    => "34JKBY103"
    irb(main):011:0> s.scan(/\d+|\D+/)
    => ["34", "JKBY", "103"]
    irb(main):012:0>
     
    Tim Greer, Feb 5, 2009
    #5
  6. shawn bright

    Tim Greer Guest


    Also, remember, there are several ways to do this. You can use an
    actual split() function with a regular expression.

    See: http://www.ruby-doc.org/core/classes/String.html
     
    Tim Greer, Feb 5, 2009
    #6
  7. shawn bright

    shawn bright Guest

    [Note: parts of this message were removed to make it a legal post.]

    way cool, thanks, all
    -sk
     
    shawn bright, Feb 5, 2009
    #7
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.