Home > Software engineering >  Check if string ends with several digits after some specific char in C#
Check if string ends with several digits after some specific char in C#

Time:09-19

I have some list that is holding several strings, for example:

List<string> list1 = new List<string>()
        {
            "REGISTER_OPTION_P2", "REGISTER_OPTION_P27", "REGISTER_OPTION_P254","REGISTER_OPTION_NOFW", "POWER_OPTION_P45JW"
        };

I Want to filter all the strings that are ending with the _P*where * is several digits only and not non-digits.

The result for the above will hold the following:

"REGISTER_OPTION_P2", "REGISTER_OPTION_P27", "REGISTER_OPTION_P254"

I know there is char.IsDigit() but it operates only on 1 digit. My case is multiple digits.

Any option to make it?

CodePudding user response:

You can use

var lst = new[] {"REGISTER_OPTION_P2", "REGISTER_OPTION_P27", "REGISTER_OPTION_P254","REGISTER_OPTION_NOFW", "POWER_OPTION_P45JW"};
var pattern = @"_P[0-9]*$";
var result = lst.Where(x => Regex.IsMatch(x, pattern, RegexOptions.RightToLeft));
foreach (var s in result)
    Console.WriteLine(s);

Output:

REGISTER_OPTION_P2
REGISTER_OPTION_P27
REGISTER_OPTION_P254

See the C# demo.

Details:

  • _P - a fixed string
  • [0-9]* - zero or more digits
  • $ - end of string.

Note the use of RegexOptions.RightToLeft that greatly enhances matching at the end of the string.

CodePudding user response:

Use the String.Replace() function

"REGISTER_OPTION_P42".Replace("REGISTER_OPTION_P",string.Empty) = "42"

or use the String.Substring() function

"REGISTER_OPTION_P42".Substring(17) = "42"

and then use .All( (c)=>char.IsDigit(c) ) to check that all remaining characters are digits.


sample code

static void Main(string[] args)
{
    var list = new List<string>(new string[] { "REGISTER_OPTION_P23", "REGISTER_OPTION_P823", "REGISTER_OPTION_P1Q6", "REGISTER_OPTION_P5" });

    var filtered = list.Where((s) => s.Replace("REGISTER_OPTION_P", string.Empty).All((c)=>char.IsDigit(c))).ToList();

    foreach (var item in filtered)
    {
        Console.WriteLine(item);
    }
    //REGISTER_OPTION_P23
    //REGISTER_OPTION_P823
    //REGISTER_OPTION_P5
}

CodePudding user response:

So the regex expression that will catch that is

P(\d $)

\d stands for digit, is more than 1, $ is the end of the string, and () specifies that it should be captured. C# should have a findAll function in regex.

One tool that is really helpful for me (because I'm not great at regex) is

https://www.autoregex.xyz/

  • Related