1

I have a list of string taken from a file. Some of this strings are in the format "Q" + number + "null" (e.g. Q98null, Q1null, Q24null, etc)

With a foreach loop I must check if a string is just like the one shown before. I use this right now

string a = "Q9null" //just for testing
if(a.Contains("Q") && a.Contains("null"))
  MessageBox.Show("ok");

but I'd like to know if there is a better way to do this with regex. Thank you!

4
  • try using pattern Q*.?null Commented Nov 8, 2014 at 13:14
  • Regex is the sensible choice, just note that using .StartsWith("Q") .EndsWidth("null") instead of .Contains would avoid false positives. Commented Nov 8, 2014 at 13:24
  • @WholsRich, but that cannot guarantee what's between "Q" and "null" Commented Nov 8, 2014 at 13:27
  • Yes, Regex is great for when you definitely need something a particular format, it was just something to keep in mind as you can find yourself doing a quick one time data filter, and a simple Char.IsDigit(a, 1) is good enough. Commented Nov 8, 2014 at 14:01

3 Answers 3

3

Your method will produce a lot of false positives - for example, it would recognize some invalid strings, such as "nullQ" or "Questionable nullability".

A regex to test for the match would be "^Q\\d+null$". The structure is very simple: it says that the target string must start in a Q, then one or more decimal digits should come, and then there should be null at the end.

Console.WriteLine(Regex.IsMatch("Q123null", "^Q\\d+null$")); // Prints True
Console.WriteLine(Regex.IsMatch("nullQ", "^Q\\d+null$"));    // Prints False

Demo.

Sign up to request clarification or add additional context in comments.

Comments

0
public static bool Check(string s)
{
    Regex regex = new Regex(@"^Q\d+null$");
    Match match = regex.Match(s);
    return match.Success;
}

Apply the above method in your code:

string a = "Q9null" //just for testing
if(Check(a))
  MessageBox.Show("ok");

Comments

0

First way: Using the Regex

Use this Regex ^Q\d+null$

Second way: Using the SubString

string s = "Q1123null";
string First,Second,Third;
First = s[0].ToString();
Second = s.Substring(1,s.Length-5);
Third = s.Substring(s.Length-4);
Console.WriteLine (First);
Console.WriteLine (Second);
Console.WriteLine (Third);

then you can check everything after this...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.