-1

I want to Extract 7 from this string GRN/GSI/2017/7 using Regex

I try it but it extract 2017

`string s1 = dt2.Rows[0]["Doc_No"].ToString();
                string i1;
                string[] numbers = Regex.Split(s1, @"\D+");
                foreach (string value in numbers)
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        i1 = value;
                        txtGRNNo.Text = i1;

                    }
                }`
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
neetha mathew
  • 39
  • 1
  • 2
  • 11

2 Answers2

2

Could you please explain what your "rule" is for extracting that digit? The code you posted will loop through all numbers after splitting the string. "\d+" is 1 or more digits. So in your case both 2017 and 7 will be matched.

Do you always only want the last number?

If so, then this could work for you:

string s1 = dt2.Rows[0]["Doc_No"].ToString();
txtGRNNo.Text = Regex.Split(s1, @"/").Last();
Janus Pienaar
  • 1,083
  • 7
  • 14
0

You could use the following RegEx patterns:

With a fixed number of characters between / : [A-Z]{0,3}\/[A-Z]{0,3}\/[0-9]{0,4}\/([0-9]*)\b

With a dynamic number of characters between / : [A-Z]*\/[A-Z]*\/[0-9]*\/([0-9]*)\b

On how to use regex, have a look at e.g. MSDN and the Match()-methode

Tobias
  • 2,945
  • 5
  • 41
  • 59