i have a String in HTML (1-3 of 3 Trip) how do i get the number 3(before trip) and convert it to int.I want to use it as a count
Found this code
public static string GetNumberFromStr(string str)
{
str = str.Trim();
Match m = Regex.Match(str, #"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$");
return (m.Value);
}
But it can only get 1 number
Regex is unnecessary overhead in your case. try this:
int ExtractNumber(string input)
{
int number = Convert.ToInt32(input.Split(' ')[2]);
return number;
}
Other useful methods for Googlers:
// throws exception if it fails
int i = int.Parse(someString);
// returns false if it fails, returns true and changes `i` if it succeeds
bool b = int.TryParse(someString, out i);
// this one is able to convert any numeric Unicode character to a double. Returns -1 if it fails
double two = char.GetNumericValue('٢')
Forget Regex. This code splits the string using a space as a delimiter and gets the number in the index 2 position.
string trip = "1-3 of 3 trip";
string[] array = trip.Split(' ');
int theNumberYouWant = int.Parse(array[2]);
Try this:
public static int GetNumberFromStr(string str)
{
str = str.Trim();
Match m = Regex.Match(str, #"^.*of\s(?<TripCount>\d+)");
return m.Groups["TripCount"].Length > 0 ? int.Parse(m.Groups["TripCount"].Value) : 0;
}
Another way to do it:
public static int[] GetNumbersFromString(string str)
{
List<int> result = new List<int>();
string[] numbers = Regex.Split(input, #"\D+");
int i;
foreach (string value in numbers)
{
if (int.TryParse(value, out i))
{
result.Add(i);
}
}
return result.ToArray();
}
Example of how to use:
const string input = "There are 4 numbers in this string: 40, 30, and 10.";
int[] numbers = MyHelperClass.GetNumbersFromString();
for(i = 0; i < numbers.length; i++)
{
Console.WriteLine("Number {0}: {1}", i + 1, number[i]);
}
Output:
Number: 4
Number: 40
Number: 30
Number: 10
Thanks to: http://www.dotnetperls.com/regex-split-numbers
If I'm reading your question properly, you'll get a string that is a single digit number followed by ' Trip' and you want to get the numeric value out?
public static int GetTripNumber(string tripEntry)
{
return int.Parse(tripEntry.ToCharArray()[0]);
}
Not really sure if you mean that you always have "(x-y of y Trip)" as a part of the string you parse...if you look at the pattern it only catches the "x-y" part thought with the acceptance of .Ee+- as seperators. If you want to catch the "y Trip" part you will have to look at another regex instead.
You could do a simple, if you change the return type to int instead of string:
Match m = Regex.Match(str, #"(?<maxTrips>\d+)\sTrip");
return m.Groups["maxTrips"].Lenght > 0 ? Convert.ToInt32(m.Groups["maxTrips"].Value) : 0;
Related
I Have a string with special chars and i have to replace those chars with an index (padded n '0' left).
Fast example for better explanation:
I have the string "0980 0099 8383 $$$$" and an index (integer) 3
result should be "0980 0099 8383 0003"
The special characters are not necessarily in sequence.
the source string could be empty or it may not contain any special characters
I've already written functions that works.
public static class StringExtensions
{
public static string ReplaceCounter(this string source, int counter, string character)
{
string res = source;
try
{
if (!string.IsNullOrEmpty(character))
{
if (res.Contains(character))
{
// Get ALL Indexes position of character
var Indexes = GetIndexes(res, character);
int max = GetMaxValue(Indexes.Count);
while (counter >= max)
{
counter -= max;
}
var new_value = counter.ToString().PadLeft(Indexes.Count, '0');
for (int i = 0; i < Indexes.Count; i++)
{
res = res.Remove(Indexes[i], 1).Insert(Indexes[i], new_value[i].ToString());
}
}
}
}
catch (Exception)
{
res = source;
}
return res;
}
private static List<int> GetIndexes(string mainString, string toFind)
{
var Indexes = new List<int>();
for (int i = mainString.IndexOf(toFind); i > -1; i = mainString.IndexOf(toFind, i + 1))
{
// for loop end when i=-1 (line.counter not found)
Indexes.Add(i);
}
return Indexes;
}
private static int GetMaxValue(int numIndexes)
{
int max = 0;
for (int i = 0; i < numIndexes; i++)
{
if (i == 0)
max = 9;
else
max = max * 10 + 9;
}
return max;
}
}
but i don't really like it (first of all because i'm passing the char as string.. and not as a char).
string source = "000081059671####=1811";
int index = 5;
string character = "#";
string result = source.ReplaceCounter(index, character);
can it be more optimized and compact?
Can some good soul help me?
Thanks in advance
EDIT
The index is variable so:
If the index is 15
string source = "000081059671####=1811";
int index = 15;
string character = "#";
string result = source.ReplaceCounter(index, character);
// result = "0000810596710015=1811"
it should be a check if the index > max number
in my code i posted above, if this case happened i remove from index the "max" value until index < max number
What is mux number? if the special chars number is 4 (as in the example below) the max number will be 9999
string source = "000081059671####=1811";
// max number 9999
Yet another edit
From a comment it seems that more than one digit can be used. In this case the counter can be converted to a string and treated as a char[] to pick the character to use in each iteration :
public static string ReplaceCounter(this string source,
int counter,
char character)
{
var sb=new StringBuilder(source);
var replacements=counter.ToString();
int r=replacements.Length-1;
for(int i=sb.Length-1;i>=0;i--)
{
if(sb[i]==character)
{
sb[i]=r>=0 ? replacements[r--] : '0';
}
}
return sb.ToString();
}
This can be used for any number of digits."0980 0099 8383 $$$$".ReplaceCounter(15,'$') produces 0980 0099 8383 0015
An edit
After posting the original answer I remembered one can modify a string without allocations by using a StringBuilder. In this case, the last match needs to be replaced with one character, all other matches with another. This ca be a simple reverse iteration :
public static string ReplaceCounter(this string source,
int counter,
char character)
{
var sb=new StringBuilder(source);
bool useChar=true;
for(int i=sb.Length-1;i>=0;i--)
{
if(sb[i]==character)
{
sb[i]=useChar?(char)('0'+counter):'0';
useChar=false;
}
}
return sb.ToString();
}
Console.WriteLine("0000##81#059671####=1811".ReplaceCounter(5,'#'));
Console.WriteLine("0980 0099 8383 $$$$".ReplaceCounter(3,'$'));
------
0000008100596710005=1811
0980 0099 8383 0003
Original Answer
Any string modification operation produces a new temporary string that need to be garbage collected. This adds up so quickly that avoiding temporary strings can result in >10x speed improvements when processing lots of text or lots of requests. That's better than using parallel processing.
You can use Regex.Replace to perform complex replacements without allocating temporary strings. You can use one of the Replace overloads that use a MatchEvaluator to produce dynamic output, not just a single value.
In this case :
var source = "0000##81#059671####=1811";
var result = Regex.Replace(source,"#", m=>m.NextMatch().Success?"0":"5");
Console.WriteLine(result);
--------
0000008100596710005=1811
Match.NextMatch() returns the next match in the source, so m.NextMatch().Success can be used to identify the last match and replace it with the index.
This would fail if the character was one of the Regex pattern characters. This can be avoided by escaping the character with Regex.Escape(string)
This can be packed in an extension method
public static string ReplaceCounter(this string source,
int counter,
string character)
{
return Regex.Replace(source,
Regex.Escape(character),
m=>m.NextMatch().Success?"0":counter.ToString());
}
public static string ReplaceCounter(this string source,
int counter,
char character)
=>ReplaceCounter(source,counter,character.ToString());
This code
var source= "0980 0099 8383 $$$$";
var result=source.ReplaceCounter(5,"$");
Returns
0980 0099 8383 0003
I would suggest such solutiuon (got rid out of helper methods:
public static class StringExtensions
{
public static string ReplaceCounter(this string source, int counter, char character)
{
string res = source;
string strCounter = counter.ToString();
bool counterTooLong = false;
int idx;
// Going from the and backwards, we fill with counter digits.
for(int i = strCounter.Length - 1; i >= 0; i--)
{
idx = res.LastIndexOf(character);
// if we run out of special characters, break the loop.
if (idx == -1)
{
counterTooLong = true;
break;
}
res = res.Remove(idx, 1).Insert(idx, strCounter[i].ToString());
}
// If we could not fit the counter, we simply throw exception
if (counterTooLong) throw new InvalidOperationException();
// If we did not fill all placeholders, we fill it with zeros.
while (-1 != (idx = res.IndexOf(character))) res = res.Remove(idx, 1).Insert(idx, "0");
return res;
}
}
Here's fiddle
I have a requirement to find and extract a number contained within a string.
For example, from these strings:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
How can I do this?
\d+ is the regex for an integer number. So
//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, #"\d+").Value;
returns a string containing the first occurrence of a number in subjectString.
Int32.Parse(resultString) will then give you the number.
Here's how I cleanse phone numbers to get the digits only:
string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());
go through the string and use Char.IsDigit
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
val = int.Parse(b);
use regular expression ...
Regex re = new Regex(#"\d+");
Match m = re.Match("test 66");
if (m.Success)
{
Console.WriteLine(string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString()));
}
else
{
Console.WriteLine("You didn't enter a string containing a number!");
}
What I use to get Phone Numbers without any punctuation...
var phone = "(787) 763-6511";
string.Join("", phone.ToCharArray().Where(Char.IsDigit));
// result: 7877636511
Regex.Split can extract numbers from strings. You get all the numbers that are found in a string.
string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, #"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
Output:
Number: 4
Number: 40
Number: 30
Number: 10
if the number has a decimal points, you can use below
using System;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine(Regex.Match("anything 876.8 anything", #"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("anything 876 anything", #"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("$876435", #"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("$876.435", #"\d+\.*\d*").Value);
}
}
}
results :
"anything 876.8 anything" ==> 876.8
"anything 876 anything" ==> 876
"$876435" ==> 876435
"$876.435" ==> 876.435
Sample : https://dotnetfiddle.net/IrtqVt
Here's a Linq version:
string s = "123iuow45ss";
var getNumbers = (from t in s
where char.IsDigit(t)
select t).ToArray();
Console.WriteLine(new string(getNumbers));
Another simple solution using Regex
You should need to use this
using System.Text.RegularExpressions;
and the code is
string var = "Hello3453232wor705Ld";
string mystr = Regex.Replace(var, #"\d", "");
string mynumber = Regex.Replace(var, #"\D", "");
Console.WriteLine(mystr);
Console.WriteLine(mynumber);
You can also try this
string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
Here is another Linq approach which extracts the first number out of a string.
string input = "123 foo 456";
int result = 0;
bool success = int.TryParse(new string(input
.SkipWhile(x => !char.IsDigit(x))
.TakeWhile(x => char.IsDigit(x))
.ToArray()), out result);
Examples:
string input = "123 foo 456"; // 123
string input = "foo 456"; // 456
string input = "123 foo"; // 123
Just use a RegEx to match the string, then convert:
Match match = Regex.Match(test , #"(\d+)");
if (match.Success) {
return int.Parse(match.Groups[1].Value);
}
string input = "Hello 20, I am 30 and he is 40";
var numbers = Regex.Matches(input, #"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
You can do this using String property like below:
return new String(input.Where(Char.IsDigit).ToArray());
which gives only number from string.
For those who want decimal number from a string with Regex in TWO line:
decimal result = 0;
decimal.TryParse(Regex.Match(s, #"\d+").Value, out result);
Same thing applys to float, long, etc...
var match=Regex.Match(#"a99b",#"\d+");
if(match.Success)
{
int val;
if(int.TryParse(match.Value,out val))
{
//val is set
}
}
The question doesn't explicitly state that you just want the characters 0 to 9 but it wouldn't be a stretch to believe that is true from your example set and comments. So here is the code that does that.
string digitsOnly = String.Empty;
foreach (char c in s)
{
// Do not use IsDigit as it will include more than the characters 0 through to 9
if (c >= '0' && c <= '9') digitsOnly += c;
}
Why you don't want to use Char.IsDigit() - Numbers include characters such as fractions, subscripts, superscripts, Roman numerals, currency numerators, encircled numbers, and script-specific digits.
Here is another simple solution using Linq which extracts only the numeric values from a string.
var numbers = string.Concat(stringInput.Where(char.IsNumber));
Example:
var numbers = string.Concat("(787) 763-6511".Where(char.IsNumber));
Gives: "7877636511"
var outputString = String.Join("", inputString.Where(Char.IsDigit));
Get all numbers in the string.
So if you use for examaple '1 plus 2' it will get '12'.
Extension method to get all positive numbers contained in a string:
public static List<long> Numbers(this string str)
{
var nums = new List<long>();
var start = -1;
for (int i = 0; i < str.Length; i++)
{
if (start < 0 && Char.IsDigit(str[i]))
{
start = i;
}
else if (start >= 0 && !Char.IsDigit(str[i]))
{
nums.Add(long.Parse(str.Substring(start, i - start)));
start = -1;
}
}
if (start >= 0)
nums.Add(long.Parse(str.Substring(start, str.Length - start)));
return nums;
}
If you want negative numbers as well simply modify this code to handle the minus sign (-)
Given this input:
"I was born in 1989, 27 years ago from now (2016)"
The resulting numbers list will be:
[1989, 27, 2016]
An interesting approach is provided here by Ahmad Mageed, uses Regex and StringBuilder to extract the integers in the order in which they appear in the string.
An example using Regex.Split based on the post by Ahmad Mageed is as follows:
var dateText = "MARCH-14-Tue";
string splitPattern = #"[^\d]";
string[] result = Regex.Split(dateText, splitPattern);
var finalresult = string.Join("", result.Where(e => !String.IsNullOrEmpty(e)));
int DayDateInt = 0;
int.TryParse(finalresult, out DayDateInt);
I have used this one-liner to pull all numbers from any string.
var phoneNumber = "(555)123-4567";
var numsOnly = string.Join("", new Regex("[0-9]").Matches(phoneNumber)); // 5551234567
string verificationCode ="dmdsnjds5344gfgk65585";
string code = "";
Regex r1 = new Regex("\\d+");
Match m1 = r1.Match(verificationCode);
while (m1.Success)
{
code += m1.Value;
m1 = m1.NextMatch();
}
Did the reverse of one of the answers to this question:
How to remove numbers from string using Regex.Replace?
// Pull out only the numbers from the string using LINQ
var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());
var numericVal = Int32.Parse(numbersFromString);
Here is my Algorithm
//Fast, C Language friendly
public static int GetNumber(string Text)
{
int val = 0;
for(int i = 0; i < Text.Length; i++)
{
char c = Text[i];
if (c >= '0' && c <= '9')
{
val *= 10;
//(ASCII code reference)
val += c - 48;
}
}
return val;
}
static string GetdigitFromString(string str)
{
char[] refArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] inputArray = str.ToCharArray();
string ext = string.Empty;
foreach (char item in inputArray)
{
if (refArray.Contains(item))
{
ext += item.ToString();
}
}
return ext;
}
here is my solution
string var = "Hello345wor705Ld";
string alpha = string.Empty;
string numer = string.Empty;
foreach (char str in var)
{
if (char.IsDigit(str))
numer += str.ToString();
else
alpha += str.ToString();
}
Console.WriteLine("String is: " + alpha);
Console.WriteLine("Numeric character is: " + numer);
Console.Read();
You will have to use Regex as \d+
\d matches digits in the given string.
string s = "kg g L000145.50\r\n";
char theCharacter = '.';
var getNumbers = (from t in s
where char.IsDigit(t) || t.Equals(theCharacter)
select t).ToArray();
var _str = string.Empty;
foreach (var item in getNumbers)
{
_str += item.ToString();
}
double _dou = Convert.ToDouble(_str);
MessageBox.Show(_dou.ToString("#,##0.00"));
Using #tim-pietzcker answer from above, the following will work for PowerShell.
PS C:\> $str = '1 test'
PS C:\> [regex]::match($str,'\d+').value
1
For instance, I have a string and I only want the character '<' to appear 10 times in the string, and create a substring where the cutoff point is the 10th appearance of that character. Is this possible?
A manual solution could be like the following:
class Program
{
static void Main(string[] args)
{
int maxNum = 10;
string initialString = "a<b<c<d<e<f<g<h<i<j<k<l<m<n<o<p<q<r<s<t<u<v<w<x<y<z";
string[] splitString = initialString.Split('<');
string result = "";
Console.WriteLine(splitString.Length);
if (splitString.Length > maxNum)
{
for (int i = 0; i < maxNum; i++) {
result += splitString[i];
result += "<";
}
}
else
{
result = initialString;
}
Console.WriteLine(result);
Console.ReadKey();
}
}
By the way, it may be better to try to do it using Regex (in case you may have other replacement rules in the future, or need to make changes, etc). However, given your problem, something like that will work, too.
You can utilize TakeWhile for your purpose, given the string s, your character < as c and your count 10 as count, following function would solve your problem:
public static string foo(string s, char c, int count)
{
var i = 0;
return string.Concat(s.TakeWhile(x => (x == c ? i++ : i) < count));
}
Regex.Matches can be used to count the number of occurrences of a patter in a string.
It also reference the position of each occurrence, the Capture.Index property.
You can read the Index of the Nth occurrence and cut your string there:
(The RegexOptions are there just in case the pattern is something different. Modify as required.)
int cutAtOccurrence = 10;
string input = "one<two<three<four<five<six<seven<eight<nine<ten<eleven<twelve<thirteen<fourteen<fifteen";
var regx = Regex.Matches(input, "<", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
if (regx.Count >= cutAtOccurrence) {
input = input.Substring(0, regx[cutAtOccurrence - 1].Index);
}
input is now:
one<two<three<four<five<six<seven<eight<nine<ten
If you need to use this procedure many times, it's bettern to build a method that returns a StringBuilder instead.
I am scraping some website content which is like this - "Company Stock Rs. 7100".
Now, what i want is to extract the numeric value from this string. I tried split but something or the other goes wrong with my regular expression.
Please let me know how to get this value.
Use:
var result = Regex.Match(input, #"\d+").Value;
If you want to find only number which is last "entity" in the string you should use this regex:
\d+$
If you want to match last number in the string, you can use:
\d+(?!\D*\d)
int val = int.Parse(Regex.Match(input, #"\d+", RegexOptions.RightToLeft).Value);
I always liked LINQ:
var theNumber = theString.Where(x => char.IsNumber(x));
Though Regex sounds like the native choice...
This code will return the integer at the end of the string. This will work better than the regular expressions in the case that there is a number somewhere else in the string.
public int getLastInt(string line)
{
int offset = line.Length;
for (int i = line.Length - 1; i >= 0; i--)
{
char c = line[i];
if (char.IsDigit(c))
{
offset--;
}
else
{
if (offset == line.Length)
{
// No int at the end
return -1;
}
return int.Parse(line.Substring(offset));
}
}
return int.Parse(line.Substring(offset));
}
If your number is always after the last space and your string always ends with this number, you can get it this way:
str.Substring(str.LastIndexOf(" ") + 1)
Here is my answer ....it is separating numeric from string using C#....
static void Main(string[] args)
{
String details = "XSD34AB67";
string numeric = "";
string nonnumeric = "";
char[] mychar = details.ToCharArray();
foreach (char ch in mychar)
{
if (char.IsDigit(ch))
{
numeric = numeric + ch.ToString();
}
else
{
nonnumeric = nonnumeric + ch.ToString();
}
}
int i = Convert.ToInt32(numeric);
Console.WriteLine(numeric);
Console.WriteLine(nonnumeric);
Console.ReadLine();
}
}
}
You can use \d+ to match the first occurrence of a number:
string num = Regex.Match(input, #"\d+").Value;
Not entirely sure this is possible, but say I have two strings like so:
"IAmAString-00001"
"IAmAString-00023"
What would be a quick'n'easy way to iterate from IAmAString-0001 to IAmAString-00023 by moving up the index of just the numbers on the end?
The problem is a bit more general than that, for example the string I could be dealing could be of any format but the last bunch of chars will always be numbers, so something like Super_Confusing-String#w00t0003 and in that case the last 0003 would be what I'd use to iterate through.
Any ideas?
You can use char.IsDigit:
static void Main(string[] args)
{
var s = "IAmAString-00001";
int index = -1;
for (int i = 0; i < s.Length; i++)
{
if (char.IsDigit(s[i]))
{
index = i;
break;
}
}
if (index == -1)
Console.WriteLine("digits not found");
else
Console.WriteLine("digits: {0}", s.Substring(index));
}
which produces this output:
digits: 00001
string.Format and a for loop should do what you want.
for(int i = 0; i <=23; i++)
{
string.Format("IAmAString-{0:D4}",i);
}
or something close to that (not sitting in front of a compiler).
string start = "IAmAString-00001";
string end = "IAmAString-00023";
// match constant part and ending digits
var matchstart = Regex.Match(start,#"^(.*?)(\d+)$");
int numberstart = int.Parse(matchstart.Groups[2].Value);
var matchend = Regex.Match(end,#"^(.*?)(\d+)$");
int numberend = int.Parse(matchend.Groups[2].Value);
// constant parts must be the same
if (matchstart.Groups[1].Value != matchend.Groups[1].Value)
throw new ArgumentException("");
// create a format string with same number of digits as original
string format = new string('0', matchstart.Groups[2].Length);
for (int ii = numberstart; ii <= numberend; ++ii)
Console.WriteLine(matchstart.Groups[1].Value + ii.ToString(format));
You could use a Regex:
var match=Regex.Match("Super_Confusing-String#w00t0003",#"(?<=(^.*\D)|^)\d+$");
if(match.Success)
{
var val=int.Parse(match.Value);
Console.WriteLine(val);
}
To answer more specifically, you could use named groups to extract what you need:
var match=Regex.Match(
"Super_Confusing-String#w00t0003",
#"(?<prefix>(^.*\D)|^)(?<digits>\d+)$");
if(match.Success)
{
var prefix=match.Groups["prefix"].Value;
Console.WriteLine(prefix);
var val=int.Parse(match.Groups["digits"].Value);
Console.WriteLine(val);
}
If you can assume that the last 5 characters are the number then:
string prefix = "myprefix-";
for (int i=1; i <=23; i++)
{
Console.WriteLine(myPrefix+i.ToString("D5"));
}
This function will find the trailing number.
private int FindTrailingNumber(string str)
{
string numString = "";
int numTest;
for (int i = str.Length - 1; i > 0; i--)
{
char c = str[i];
if (int.TryParse(c.ToString(), out numTest))
{
numString = c + numString;
}
}
return int.Parse(numString);
}
Assuming all your base strings are the same, this would iterate between strings.
string s1 = "asdf123";
string s2 = "asdf127";
int num1 = FindTrailingNumber(s1);
int num2 = FindTrailingNumber(s2);
string strBase = s1.Replace(num1.ToString(), "");
for (int i = num1; i <= num2; i++)
{
Console.WriteLine(strBase + i.ToString());
}
I think it would be better if you do the search from the last (Rick already upvoted you since it was ur logic :-))
static void Main(string[] args)
{
var s = "IAmAString-00001";
int index = -1;
for (int i = s.Length - 1; i >=0; i--)
{
if (!char.IsDigit(s[i]))
{
index = i;
break;
}
}
if (index == -1)
Console.WriteLine("digits not found");
else
Console.WriteLine("digits: {0}", s.Substring(index));
Console.ReadKey();
}
HTH
If the last X numbers are always digits, then:
int x = 5;
string s = "IAmAString-00001";
int num = int.Parse(s.Substring(s.Length - x, x));
Console.WriteLine("Your Number is: {0}", num);
If the last digits can be 3, 4, or 5 in length, then you will need a little more logic:
int x = 0;
string s = "IAmAString-00001";
foreach (char c in s.Reverse())//Use Reverse() so you start with digits only.
{
if(char.IsDigit(c) == false)
break;//If we start hitting non-digit characters, then exit the loop.
++x;
}
int num = int.Parse(s.Substring(s.Length - x, x));
Console.WriteLine("Your Number is: {0}", num);
I'm not good with complicated RegEx. Because of this, I always shy away from it when maximum optimization is unnecessary. The reason for this is RegEx doesn't always parse strings the way you expect it to. If there is and alternate solution that will still run fast then I'd rather go that route as it's easier for me to understand and know that it will work with any combination of strings.
For Example: if you use some of the other solutions presented here with a string like "I2AmAString-000001", then you will get "2000001" as your number instead of "1".