Shriram Sapate
Shriram Sapate

Reputation: 175

Check if string contains character and number

How do I check if a string contains the following characters "RM" followed by a any number or special character(-, _ etc) and then followed by "T"?

Ex: thisIsaString ABRM21TC = yes, contains "RM" followed by a number and followed by "T"

Ex: thisIsaNotherString RM-T = yes, contain "RM" followed by a special character then followed by "T"

Upvotes: 0

Views: 1595

Answers (5)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You can do it with a simple regular expression:

var match = Regex.Match(s, "RM([^T]+)T");
  • Check if the pattern is present by calling match.Success.
  • Get the captured value by calling match.Groups[1].

Here is a demo (on ideone: link):

foreach (var s in new[] {"ABRM21TC", "RM-T", "RxM-T", "ABR21TC"} ) {
    var match = Regex.Match(s, "RM([^T]+)T");
    Console.WriteLine("'{0}' - {1} (Captures '{2}')", s, match.Success, match.Groups[1]);
}

It prints

'ABRM21TC' - True (Captures '21')
'RM-T' - True (Captures '-')
'RxM-T' - False (Captures '')
'ABR21TC' - False (Captures '')

Upvotes: 2

peter.petrov
peter.petrov

Reputation: 39457

Try this regexp.

[^RM]*RM[^RMT]+T[^RMT]*

Here is a sample program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication12
{
    class Program
    {
        static void Main(string[] args)
        {
            String rg = "[^RM]*RM[^RMT]+T[^RMT]*";
            string input = "111RM----T222";

            Match match = Regex.Match(input, rg, RegexOptions.IgnoreCase);

            Console.WriteLine(match.Success);
        }

    }

}

Upvotes: 2

Bas
Bas

Reputation: 27095

You should play around with more sample data especially regarding special characters, you can use regexpal, I have added the two cases and an expression to get you started.

Upvotes: 1

wakthar
wakthar

Reputation: 718

Use regular expressions

http://www.webresourcesdepot.com/learn-test-regular-expressions-with-the-regulator/

The Regulator is an advanced, free regular expressions testing and learning tool. It allows you to build and verify a regular expression against any text input, file or web, and displays matching, splitting or replacement results within an easy to understand, hierarchical tree.

Upvotes: 1

Matthew Verstraete
Matthew Verstraete

Reputation: 6781

Your going to want to check the string using a regex (regular expression). See this MSDN for info on how to do that

http://msdn.microsoft.com/en-us/library/ms228595.aspx

Upvotes: 4

Related Questions