0

I need to get only the last number from the string. The string contains pattern of string+integer+string+integer i.e. "GS190PA47". I need to get only 47 from the string.

Thank you

3
  • Google "regular expressions", and try this tool to experiment derekslager.com/blog/posts/2007/09/… Commented Apr 5, 2013 at 9:17
  • If you need only 47 , the easiest way is substring the last two character of your string :) Commented Apr 5, 2013 at 9:21
  • is the format fix? 2 string + 3 int + 2 string + 2 int? Commented Apr 5, 2013 at 9:21

5 Answers 5

4

A simple regular expression chained to the end of the string for any number of integer digits

string test = "GS190PA47";
Regex r = new Regex(@"\d+$");
var m = r.Match(test);

if(m.Success == false)
    Console.WriteLine("Ending digits not found");
else
    Console.WriteLine(m.ToString());
Sign up to request clarification or add additional context in comments.

Comments

1
string input = "GS190PA47";
var x = Int32.Parse(Regex.Matches(input, @"\d+").Cast<Match>().Last().Value);

If string always ends with number, you can simply use \d+$ pattern, as Steve suggests.

Comments

0

you can try this regex:

(\d+)(?!.*\d)

you can test it with this online tool: link

Comments

0

Try this:

string input = "GS190PA47";

Regex r = new Regex(@"\d+\D+(\d+)");
int number = int.Parse(r.Match(input).Groups[1].Value);

Pattern means we find set of digits (190), next set of non-digit chars (PA) and finally sought-for number.

Don't forget include using System.Text.RegularExpressions directive.

Comments

0

Not sure if this is less or more efficient than RegEx (Profile it)

 string input = "GS190PA47";
 var x = Int32.Parse(new string(input.Where(Char.IsDigit).ToArray()));

Edit:

Amazingly it is actually much faster than regex

var a = Stopwatch.StartNew();

        for (int i = 0; i < 10000; i++)
        {
            string input = "GS190PA47";
            var x = Int32.Parse(new string(input.Reverse().TakeWhile(Char.IsDigit).Reverse().ToArray()));
        }
        a.Stop();
        var b = a.ElapsedMilliseconds;

        Console.WriteLine(b);

        a = Stopwatch.StartNew();

        for (int i = 0; i < 10000; i++)
        {
            string input = "GS190PA47";
            var x = Int32.Parse(Regex.Matches(input, @"\d+").Cast<Match>().Last().Value);
        }
        a.Stop();
         b = a.ElapsedMilliseconds;

        Console.WriteLine(b);

2 Comments

Granted not quite what you were after but food for thought. Could use SkipWhile or Substring if the structure is deterministic.
This would get all numbers in the input (joined together), not just the last one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.