1

I want to validate a string based on a custom format: ___.___ or ___,___, 3 numbers followed by a dot or comma followed by 3 numbers (e.g. 123.456 or 123,456).

Currently, I have following code:

string InputText = "123.456"
bool result, result1, result2;
int test, test2;
result = Int32.TryParse(InputText.Substring(0, 3), out test);
result1 = (InputText[3] == '.' || InputText[3] == ',') ? true : false;
result2 = Int32.TryParse(InputText.Substring(4, 3), out test2);

if (result == false || result1 == false || result2 == false)
{
    Console.WriteLine("Error! Wrong format.");
}

This works just fine, however, this seems rather inefficient and unnecessarily complex; is there an alternative to this?

1
  • 1
    have you tried \d{3}[.,]\d{3} Commented Aug 2, 2014 at 16:11

3 Answers 3

2

Is there an alternative to this? Yes you can use Regex.IsMatch to do this.

String s = "123.456";
if (!Regex.IsMatch(s, @"^\d{3}[.,]\d{3}$")) {
    Console.WriteLine("Error! Wrong format.");
}

Explanation:

^        # the beginning of the string
 \d{3}   #   digits (0-9) (3 times)
 [.,]    #   any character of: '.', ','
 \d{3}   #   digits (0-9) (3 times)
$        # before an optional \n, and the end of the string
Sign up to request clarification or add additional context in comments.

Comments

1

Pattern to validate 3 numbers followed by a dot or comma followed by 3 numbers is,

^\d{3}[,.]\d{3}$

DEMO

Comments

1

Aditional to Avinash answer if you want to capture the numbers matching the format you can use the following regex:

\b(\d{3}[.,]\d{3})\b

Working demo

enter image description here

2 Comments

While validating a string, it's better to give start and end patterns. Is screen-shot necessary?
@AvinashRaj you are totally right, I missed the part of "I want to validate" though about if a string matches the regex

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.