From: Josh Cheek Date: 2010-12-05T05:29:51+09:00 Subject: Re: Split a string at a certain character --0016e68db81c1bf09304969b8482 Content-Type: text/plain; charset=ISO-8859-1 On Sat, Dec 4, 2010 at 1:31 PM, Matt Slay wrote: > I am writig an app where the user will enter a string and then I need to > split that string into two parts and then I can process the two parts > from there and show them some output. > > I need help with the best Ruby way to split the string into the two > parts... > > Here are examples of some typical user inputs, and then what it must be > split into for further processing. Hopefully you will see a pattern to > it and can help me. (Note: sometimes there will be a space between the > two parts, but some user may omit the space between [part 1] and [part > 2], so I must handle both cases) > > (They will not enter the quotes, I just did it for clarity) > > Examples (several to help you see the pattern): > > "80e6" must split to "80" and "e6" > > "80 e6" must split to "80" and "e6" > > "12.5H7" must split to "12.5" and "H7 > > "120 JS11" must split to "120" and "JS11" > > "20.8a11" must split to "20.8" and "a11" > > "45.50 h2" must split to "45.50" and "h2" > > "90.2F3" must split to "90.2" and "F3" > > "45js4" must split to "45" and "js4" > > > Here is the basic pattern, in words: > > [part 1] followed by [part 2] > > which is to say: > > [part 1 = an integer or floating point number] followed by [part 2 = a > single or double set of letters (a-z or A-Z), which is then folled by an > integer] > > If there is a space between [part 1] and [part 2], it needs to be > ignored. > > > If you are really interested in what all this is for, you can read on... > (it may help you see the overall picture. > > Eventually, [part 1] will be converted to a floating point number, and > [part 2] will be used to look up some other floating point number in a > database table which is then used as a variance amount that will be > applied to [part 1]. > > -- > Posted via http://www.ruby-forum.com/. > > This meets all of your cases, though none of them include negative signs at the beginning, and you haven't specified how it should behave for bad data (ie either malformed, or not as prestine as the inputs you've supplied). require 'test/unit' def mysplit(str) str[/^(\d+(?:\.\d+)?)\s*([^$]*)$/] return $1 , $2 end class MysplitTester < Test::Unit::TestCase def test_1 assert_equal [ "80" , "e6" ] , mysplit( "80e6" ) end def test_2 assert_equal [ "80" , "e6" ] , mysplit( "80 e6" ) end def test_3 assert_equal [ "12.5" , "H7" ] , mysplit( "12.5H7" ) end def test_4 assert_equal [ "120" , "JS11" ] , mysplit( "120 JS11" ) end def test_5 assert_equal [ "20.8" , "a11" ] , mysplit( "20.8a11" ) end def test_6 assert_equal [ "45.50" , "h2" ] , mysplit( "45.50 h2" ) end def test_7 assert_equal [ "90.2" , "F3" ] , mysplit( "90.2F3" ) end def test_8 assert_equal [ "45" , "js4" ] , mysplit( "45js4" ) end end --0016e68db81c1bf09304969b8482--