Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string into a string and an integer

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.

like image 795
NickEckhart Avatar asked May 31 '26 19:05

NickEckhart


1 Answers

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"]
like image 106
Avinash Raj Avatar answered Jun 02 '26 07:06

Avinash Raj