Dumbo
Dumbo

Reputation: 14142

How to check if a string is built up using only specific characters

I need to check if a string is only built up using 1, 0 and comma. It should also starts with either 0 or 1 and also ends with 0 or 1:

The checking for start and end can be done like this (Or if you think it can be improved peplase let me know!)

if ((text.StartsWith("0") || text.StartsWith("1")) //Starts with 0 or 1
    && (text.EndsWith("0") || text.EndsWith("1")) //Ends with 0 or 1
    && //How to check if it only has 0, 1 and comma?            )
{
    //Do Something!
}

Upvotes: 0

Views: 172

Answers (6)

Nazmul
Nazmul

Reputation: 7218

You can try this,

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[01][01,]+?[01]");
if (!reg.IsMatch("3452"))
{
    Response.Write("Does Not Match");
}

if (reg.IsMatch("01111,1"))
{
    Response.Write("Yes Match!");
}

Upvotes: 0

shenhengbin
shenhengbin

Reputation: 4294

Is it one way ?

if (value.Trim("01,".ToCharArray()).Length == 0 )

Upvotes: 0

Craigt
Craigt

Reputation: 3580

Use a regular expression like this [01][01,]+?[01]. Im sure there could be better regex patterns to use. But that would work.

if(Regex.IsMatch(mystring, "[01][01,]+?[01]"))
   //yes it matches;

This regex pattern will look for a 0 or a 1 and then an optional sequence of 0, 1 or "," and then ending in a 0 or a 1 again.

Upvotes: 0

Adam
Adam

Reputation: 15803

if (Regex.IsMatch("0101,1010", "^[01][01,]*[01]$"))
{
     doSomething();
}

you need to add

using System.Text.RegularExpressions;

to the top of your file for this to work.

Upvotes: 0

Abdul Munim
Abdul Munim

Reputation: 19217

You can use Regex, try this:

if (new Regex("^[01][01,]*[01]$").Match(text).Success)
{
   // do your stuffs
}

Upvotes: 4

Lloyd Powell
Lloyd Powell

Reputation: 18810

public bool CheckMyString(string text)
{
    if ((text.StartsWith("0") || text.StartsWith("1")) 
       && (text.EndsWith("0") || text.EndsWith("1")))
    {
      foreach (char c in text)
      {
         if (c != "1" && c != "0" && c != ",")
         {
            return false;
         }
      }
    }
    else
    {
       return false;
    }

    return true;
}

Upvotes: 1

Related Questions