I have several strings that contain one or more digits and may also contain one or more letters following the digits (caps on letters don't matter). The strings follow the following regex pattern:
[0-9]+[a-zA-z]*
and may look like:
"15791"
"14810A"
"10480ABCD"
"5ABCDEFGH"
If one of the strings above contains non-numerical characters, how do I split the numbers (first part) into an integer and the letters (second part) into a string?
I know I can split a string like this:
array = "1,2,3,4".split(',')
But this doesn't help since I don't have a separator.
Use a positive lookbehind assertion based regex in string.split.
> "10480ABCD".split(/(?<=\d)(?=[A-Za-z])/)
=> ["10480", "ABCD"]
(?<=\d) Positive lookbehind which asserts that the match must be preceded by a digit character.
(?=[A-Za-z]) which asserts that the match must be followed by an alphabet. So the above regex would match the boundary which exists between a digit and an alphabet. Splitting your input according to the matched boundary will give you the desired output.
OR
Use string.scan
> "10480ABCD".scan(/\d+|[A-Za-z]+/)
=> ["10480", "ABCD"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With