Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first numbers from String

Tags:

How to get the first numbers from a string?

Example: I have "1567438absdg345"

I only want to get "1567438" without "absdg345", I want it to be dynamic, get the first occurrence of Alphabet index and remove everything after it.

like image 560
Alaa Osta Avatar asked Jan 31 '12 13:01

Alaa Osta


People also ask

How do you extract the first digit of a string in Python?

Making use of isdigit() function to extract digits from a Python string. Python provides us with string. isdigit() to check for the presence of digits in a string. Python isdigit() function returns True if the input string contains digit characters in it.

How do you extract the first number in Python?

To get the first digit, we can use the Python math log10() function. In the loop example, we divided by 10 until we got to a number between 0 and 10. By using the log10() function, we can find out exactly how many times we need to divide by 10 and then do the division directly.

How do you find a number in a string?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.


Video Answer


2 Answers

You can use the TakeWhile extension methods to get characters from the string as long as they are digits:

string input = "1567438absdg345";  string digits = new String(input.TakeWhile(Char.IsDigit).ToArray()); 
like image 162
Guffa Avatar answered Oct 20 '22 14:10

Guffa


The Linq approach:

string input = "1567438absdg345"; string output = new string(input.TakeWhile(char.IsDigit).ToArray()); 
like image 23
BrokenGlass Avatar answered Oct 20 '22 15:10

BrokenGlass