1

I have a string in ruby whose initial characters would be numbers and the last character would always be a letter. Some of the examples are: 2C, 1P, 45H, 135D.

I want to get an array which would have 2 objects, first would be the number and second would be the character.

Eg: for 2C, array would be [2, C]
    for 45H, array would be [45, H]
    for 135D, array would be [135, D]

I tried my_string[/(\d+)([A-Z])$/].split(//, 1), but it gives me an entire string in an array. Like ["2C"], ["45H"]

Am I missing something here?

4
  • Try splitting by (?<=\d)(?=[A-Z]) instead...I can explain and post as answer if it works. Commented May 9, 2014 at 16:36
  • Okay let me try and will let you know on the result Commented May 9, 2014 at 16:37
  • It gave me an empty array Commented May 9, 2014 at 16:38
  • I did my_string[/(?<=\d)(?=[A-Z])/].split(//,1) Commented May 9, 2014 at 16:39

2 Answers 2

4

I had to do some quick Googling to see how to use Ruby's split, but here is how you want to do it:

print '2C'.split(/(?<=\d)(?=[A-Z])/);
// ["2", "C"]

The expression works by doing a lookbehind ((?<=...)) and a lookahead ((?=...)). This means we will match the spot that has a digit to the left and a letter to the right.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh you using regex directly inside split. Hmm nice ways. Let me give it a try.
No problem, glad it helped -- short and sweet :)
Ah, using Ruby's split() is easier than I thought. +1
1

You can use scan:

'150D'.scan(/\d+|\w/)
# => ["150", "D"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.