Hi @Haviv Elbsz , Welcome to Microsoft Q&A,
I think you should use it in conjunction with code judgment.
Don't when the number in the obtained group is greater than 3.
make judgments
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace xxx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "6";
textBox2.Text = "34sad 464dff";
textBox3.Text = "34sad 464dff asdas 45647ff";
textBox4.Text = "34sad 464dff 546asdas 45647ff";
}
//Use the regular \d+( \d+){0,2} to determine that the content in the textbox is returned as a list. If the elements of the list are more than 3 or equal to 0, false is returned.
static List<int> ExtractNumbers(string input)
{
List<int> result = new List<int>();
//Define regular expression
Regex regex = new Regex(@"\d+( \d+)?( \d+)?");
// Match string
MatchCollection matches = regex.Matches(input);
//Extract matching numbers
foreach (Match match in matches)
{
foreach (Capture capture in match.Captures)
{
int number;
if (int.TryParse(capture.Value, out number))
{
result.Add(number);
}
}
}
return result;
}
static bool isValid(List<int> numbers)
{
if (numbers.Count == 0 || numbers.Count > 3)
{
return false;
}
else
{
return true;
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
List<int> numbers = ExtractNumbers(c.Text);
if (isValid(numbers))
{
c.Text += "Valid";
}
else
{
c.Text += "inValid";
}
}
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.