0

I have a string array

string [] ar = { "net" , "com" , "org"};

and I want the label writes "true" when the user enter a website example ends with a string in the array

I tried this:

   private void timer1_Tick(object sender, EventArgs e)
    {
        foreach ( string ex in ar)
        {
            if (Regex.IsMatch(txtbox.Text, @"^(www\.)([\w]+)\.(" + ex + ")$"))
            {
                lbl.Text = "True";
            }
            else
            {
                lbl.Text = "False";
            }
        }
    }

When I write for example "www.google.com", the label still writes false. Only when I write "www.google.org" the label writes true.

2
  • Try lbl.Text = ar.Any(ex => Regex.IsMatch(txtbox.Text, @"^(www\.)([\w]+)\.(" + ex + ")$"))) ? "True" : "False"; instead Commented Oct 22, 2015 at 15:22
  • EndWith should be really enough, regex is not necessary. Commented Oct 22, 2015 at 15:26

2 Answers 2

7

You'll need to stop your foreach iteration as soon as you hit the first match. Or, better yet,

lbl.Text = ar.Any(s => Regex.IsMatch(txtbox.Text, "..." + s + "...")) ? "True" : "False"

Plus, be careful with timers in a WinForms applications: you can only safely use System.Windows.Forms.Timer, not System.Threading.Timer.

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

Comments

0

You are using foreach loop which are completing its all ittrations, so when ittration is compare with your condition then remove the control from loop e.g. org at the last of array index thatswhy it found at last of the lopp ittrations, edit your code as.

 foreach ( string ex in ar)
        {
            if (Regex.IsMatch(txtbox.Text, @"^(www\.)([\w]+)\.(" + ex + ")$"))
            {
                lbl.Text = "True";
                return;
            }
            else
            {
                lbl.Text = "False";
            }
        }

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.