Reputation: 37
Could someone explain how i can verify every field of a string? The string "45-78". I want to verify the first two and last two fields of the string (If they have the numbers required) and the middle one (if it has a certain type of char(-)). Is there a way to verify the string this way? If there is can someone give me a quick example? Thanks to all!
Upvotes: 0
Views: 93
Reputation: 34421
Here is a much simplier Regex
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "45-78";
string pattern = @"\d+-\d+";
Boolean match = Regex.IsMatch(input, pattern);
}
}
}
Upvotes: 2
Reputation: 1474
If your expected input is always of the type wx-yz
where w,x,y,z being numbers.
You can check whether the string contains the special character.
Then you can split the string and check for each part if it is a number or not. If it is number, you can further check if it belongs to some particular range or do other validations as required.
If everything is as expected, do further processing.
string input = "45-78";
if(input.Contains("-"))
{
// the string contains the special character which separates our two number values
string firstPart = input.Split('-')[0]; // now we have "45"
string secondPart = input.Split('-')[1]; // now we have "78"
int firstNumber;
bool isFirstPartInt = Int32.TryParse(firstPart, out firstNumber);
bool isResultValid = true;
if(isFirstPartInt)
{
//check for the range to which the firstNumber should belong
}
else isResultValid = false;
int secondNumber;
bool isFirstPartInt = Int32.TryParse(secondPart, out secondNumber);
if(isFirstPartInt)
{
//check for the range to which the secondNumber should belong
}
else isResultValid = false;
if(isResultValid)
{
// string was in correct format and both the numbers are as expected.
// proceed with further processing
}
}
else
{
// the input string is not in correct format
}
Upvotes: 3
Reputation: 152
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
Regex regex = new Regex(@"^[0-9]{2}-[0-9]{2}$");
Match match = regex.Match("45-55");
if (match.Success)
{
Console.WriteLine("Verified");
}
}
}
Upvotes: 2