Reputation: 4339
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.
Upvotes: 28
Views: 46675
Reputation: 137
I know this question is 10 years old but just incase someone else comes across it. The accepted answer will only give you the first number if the number is right at the start of the input string.
When your string starts with anything but a digit it will return a empty string. You would first need to know the index of the first digit and do a substring before using the accepted answer.
string input = "abc123def456ghi";
string digits = null;
if (!string.IsNullOrEmpty(input))
{
var indexFirstDigit = input.IndexOfAny("0123456789".ToCharArray());
if (indexFirstDigit >= 0)
{
digits = new String(input.Substring(indexFirstDigit).TakeWhile(Char.IsDigit).ToArray());
}
}
Though using regex would require fewer lines
string input = "abc012def345ghi";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[\\d]+");
string digits = reg.Match(input).Value;
Upvotes: 0
Reputation: 1531
This way you get the first digit from the string.
string stringResult = "";
bool digitFound = false;
foreach (var res in stringToTest)
{
if (digitFound && !Char.IsDigit(res))
break;
if (Char.IsDigit(res))
{
stringResult += res;
digitFound = true;
}
}
int? firstDigitInString = digitFound ? Convert.ToInt32(stringResult) : (int?)null;
Another alternative that should do it:
string[] numbers = Regex.Split(input, @"\D+");
I dont know why I got an empty string as a result in the numbers list above though?
Solved it like below, but seems a like the regex should be improved to do it immediately.
string[] numbers = Regex.Split(firstResult, @"\D+").Where(x => x != "").ToArray();
Upvotes: 1
Reputation: 12608
You can loop through the string and test if the current character is numeric via Char.isDigit
.
string str = "1567438absdg345";
string result = "";
for (int i = 0; i < str.Length; i++) // loop over the complete input
{
if (Char.IsDigit(str[i])) //check if the current char is digit
result += str[i];
else
break; //Stop the loop after the first character
}
Upvotes: 7
Reputation: 48415
forget the regex, create this as a helper function somewhere...
string input = "1567438absdg345";
string result = "";
foreach(char c in input)
{
if(!Char.IsDigit(c))
{
break;
}
result += c;
}
Upvotes: 4
Reputation: 3438
Please try this
string val = "1567438absdg345";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[1-9][0-9]*");
string valNum = reg.Match(val).Value;
Upvotes: 1
Reputation: 2190
An old-fashioned Regular expressionist way:
public long ParseInt(string str)
{
long val = 0;
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^([\d]+).*$");
System.Text.RegularExpressions.Match match = reg.Match(str);
if (match != null) long.TryParse(match.Groups[1].Value, out val);
return val;
}
If it cannot parse, the method returns 0.
Upvotes: 3
Reputation: 92976
Or the regex approach
String s = "1567438absdg345";
String result = Regex.Match(s, @"^\d+").ToString();
^
matches the start of the string and \d+
the following digits
Upvotes: 15
Reputation: 1007
Another approach
private int GetFirstNum(string inp)
{
string final = "0"; //if there's nothing, it'll return 0
foreach (char c in inp) //loop the string
{
try
{
Convert.ToInt32(c.ToString()); //if it can convert
final += c.ToString(); //add to final string
}
catch (FormatException) //if NaN
{
break; //break out of loop
}
}
return Convert.ToInt32(final); //return the int
}
Test:
Response.Write(GetFirstNum("1567438absdg345") + "<br/>");
Response.Write(GetFirstNum("a1567438absdg345") + "<br/>");
Result:
1567438
0
Upvotes: 2
Reputation: 700262
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());
Upvotes: 49
Reputation: 160862
The Linq approach:
string input = "1567438absdg345";
string output = new string(input.TakeWhile(char.IsDigit).ToArray());
Upvotes: 25