Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String parsing, extracting numbers and letters

What's the easiest way to parse a string and extract a number and a letter? I have string that can be in the following format (number|letter or letter|number), i.e "10A", "B5", "C10", "1G", etc.

I need to extract the 2 parts, i.e. "10A" -> "10" and "A".

Update: Thanks to everyone for all the excellent answers

like image 806
Matt Warren Avatar asked Apr 09 '09 16:04

Matt Warren


People also ask

How do I extract numbers from a string?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).

How do I extract numbers from text and numbers in Excel?

Select all cells with the source strings. On the Extract tool's pane, select the Extract numbers radio button. Depending on whether you want the results to be formulas or values, select the Insert as formula box or leave it unselected (default).

How do I extract numbers from alphanumeric strings in Python?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.

How do I extract a number from a string in Excel?

Extract Numbers from String in Excel (using VBA) Since we have done all the heavy lifting in the code itself, all you need to do is use the formula =GetNumeric(A2). This will instantly give you only the numeric part of the string.


1 Answers

Easiest way is probably to use regular expressions.

((?<number>\d+)(?<letter>[a-zA-Z])|(?<letter>[a-zA-Z])(?<number>\d+))

You can then match it with your string and extract the value from the groups.

Match match = regex.Match("10A");
string letter = match.Groups["letter"].Value;
int number = int.Parse(match.Groups["number"].Value);
like image 133
Samuel Avatar answered Nov 12 '22 21:11

Samuel