1

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?

axcelenator
  • 1,497
  • 3
  • 18
  • 42

3 Answers3

4

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • though 0-9 aren't the only digits in this world maybe consider `\d` instead (OP didn't spedify the limitation to only 0-9) – Rand Random Sep 19 '22 at 13:44
  • 2
    @RandRandom Following the [`\d` less efficient than \[0-9\]](https://stackoverflow.com/q/16621738/3832970), I tend to use explicit digit patterns when it comes to ASCII digits (as shown in the examples). If any Unicode digits like `۱`, `௫` or `৫` can appear after `_P`, yes, `\d*` would be best. – Wiktor Stribiżew Sep 19 '22 at 13:48
2

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/

Eric Yang
  • 2,678
  • 1
  • 12
  • 18
2

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
}
John Alexiou
  • 28,472
  • 11
  • 77
  • 133