skip to Main Content

Need to get three strings from the below mentioned string, need the possible solution in C# and ASP.NET:

"componentStatusId==2|3,screeningOwnerId>0"

I need to get ‘2’,’3′ and ‘0’ using a regular expression in C#

2

Answers


  1. Use following regex and capture your values from group 1, 2 and 3.

    componentStatusId==(d+)|(d+),screeningOwnerId>(d+)
    

    Demo

    For generalizing componentStatusId and screeningOwnerId with any string, you can use w+ in the regex and make it more general.

    w+==(d+)|(d+),w+>(d+)
    

    Updated Demo

    Login or Signup to reply.
  2. If all you want is the numbers from a string then you could use the regex in this code:

            string re = "(?:\b(\d+)\b[^\d]*)+";
            Regex regex = new Regex(re);
    
            string input = "componentStatusId==2|3,screeningOwnerId>0";
    
            MatchCollection matches = regex.Matches(input);
    
            for (int ii = 0; ii < matches.Count; ii++)
            {
                Console.WriteLine("Match[{0}]  // of 0..{1}:", ii, matches.Count - 1);
                DisplayMatchResults(matches[ii]);
            }
    

    Function DisplayMatchResults is taken from this Stack Overflow answer.

    The Console output from the above is:

    Match[0]  // of 0..0:
    Match has 1 captures
      Group  0 has  1 captures '2|3,screeningOwnerId>0'
           Capture  0 '2|3,screeningOwnerId>0'
      Group  1 has  3 captures '0'
           Capture  0 '2'
           Capture  1 '3'
           Capture  2 '0'
        match.Groups[0].Value == "2|3,screeningOwnerId>0"
        match.Groups[1].Value == "0"
        match.Groups[0].Captures[0].Value == "2|3,screeningOwnerId>0"
        match.Groups[1].Captures[0].Value == "2"
        match.Groups[1].Captures[1].Value == "3"
        match.Groups[1].Captures[2].Value == "0"
    

    Hence the numbers can be seen in match.Groups[1].Captures[...].



    Another possibility is to use Regex.Split where the pattern is "non digits". The results from the code below will need post processing to remove empty strings. Note that Regex.Split does not have the StringSplitOptions.RemoveEmptyEntries of the string Split method.

            string input = "componentStatusId==2|3,screeningOwnerId>0";
            string[] numbers = Regex.Split(input, "[^\d]+");
            for (int ii = 0; ii < numbers.Length; ii++)
            {
                Console.WriteLine("{0}:  '{1}'", ii, numbers[ii]);
            }
    

    The output from this is:

    0:  ''
    1:  '2'
    2:  '34'
    3:  '0'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search