How to find an alphanumeric substring

mauede 221 Reputation points

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";
Console.WriteLine("String OK)");
Console.WriteLine("string KO");

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

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,601 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114.4K Reputation points

    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