In my current project I have to work alot with substring and I'm wondering if there is an easier way to get out numbers from a string.
Example: I have a string like this: 12 text text 7 text
I want to be available to get out first number set or second number set. So if I ask for number set 1 I will get 12 in return and if I ask for number set 2 I will get 7 in return.
Thanks!
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.
2. Extracting Numbers from the Right of a Text or Number String by Combining RIGHT, LEN, MIN & SEARCH Functions. Press Enter & then use Fill Handle to autofill the rest of the cells. MIN function is used to find the lowest digit or number from an array.
This will create an array of integers from the string:
using System.Linq;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string text = "12 text text 7 text";
int[] numbers = (from Match m in Regex.Matches(text, @"\d+") select int.Parse(m.Value)).ToArray();
}
}
Try using regular expressions, you can match [0-9]+
which will match any run of numerals within your string. The C# code to use this regex is roughly as follows:
Match match = Regex.Match(input, "[0-9]+", RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
// here you get the first match
string value = match.Groups[1].Value;
}
You will of course still have to parse the returned strings.
Looks like a good match for Regex
.
The basic regular expression would be \d+
to match on (one or more digits).
You would iterate through the Matches
collection returned from Regex.Matches
and parse each returned match in turn.
var matches = Regex.Matches(input, "\d+");
foreach(var match in matches)
{
myIntList.Add(int.Parse(match.Value));
}
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