Reputation: 7100
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?
Upvotes: 1
Views: 89
Reputation: 20486
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.
Upvotes: 4