How to find an alphanumeric substring

mauede 221 Reputation points
2022-04-12T14:27:17.11+00:00

This is a trivial problem but I cannot get a solution.
I am trying to make my code recognize strings like the following:
"PTV1_3000", "ITV3_4000"
The sub-string should contain a root-like "PTV", "ITV", "CTV" followed by one or more integer numbers followed by "_".
I tried different flavors of the following expression:

string str = "ITV2_123";
if(str.Contains("ITV[0-9]*$_"))
{
Console.WriteLine("String OK)");
}
else
{
Console.WriteLine("string KO");
}
Console.ReadKey();

Is it possible to find alphanumeric sub-strings in a string?
Thank you so much.

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-04-12T14:36:12.323+00:00

    Try using Regular Expressions:

    string str = "ITV2_123";
    
    if( Regex.IsMatch( str, @"(P|I|C)TV\d+_\d+" ) )
    {
        Console.WriteLine( "String OK" );
    }
    

    The expression can be adjusted for your specific rules.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.