b3r3ch1t
b3r3ch1t

Reputation: 165

Validate String With Regex

I'm trying to validate a string with this regex

var regexAgencia = new Regex("^(?!0000)([0-9]{4})");
var result = regexAgencia.IsMatch(agencia);

Valid Options:

N-X
NN-X
NNN-X
NNNN-X
N
NN 
NNN 
NNNN

Invalid Options:

0-X 
00-X 
000-X 
0000-X
0
00
000
0000

Where N is any number 0-9 and X can be X or 0-9

When I validade this "014777417" the regex return true

I need help to write a regex to validade this string with this rules.

Upvotes: 0

Views: 357

Answers (3)

SamWhan
SamWhan

Reputation: 8332

This should do it for you:

^(?=\d*[1-9])\d{1,4}(?:-[X\d])?$

It starts with a positive look ahead to ensure a digit other than zero is present ((?=\d*[1-9])). Thereafter it matches 1-4 digits, optionally followed by a hyphen and a digit or X.

See it here at regex101.

Upvotes: 2

Andrew Morton
Andrew Morton

Reputation: 25013

It would be easier to have two tests: one to check if it could be valid, followed by one to exclude the special case of all leading zeros being invalid:

static void Main(string[] args)
{
    string[] agencias = { "", "1234-5", "0-9", "014777417", "0000", "1-23", "01-0", "1-234 abcd", "0123-4" };

    var regexAgenciaValid = new Regex("^(([0-9]{1,4})(-[0-9])?)$");
    var regexAgenciaInvalid = new Regex("^((0{1,4})(-[0-9])?)$");

    foreach (string agencia in agencias)
    {
        var result = regexAgenciaValid.IsMatch(agencia) && !regexAgenciaInvalid.IsMatch(agencia);
        Console.WriteLine(agencia + " " + result);
    }

    Console.ReadLine();

}

Output:

 False
1234-5 True
0-9 False
014777417 False
0000 False
1-23 False
01-0 True
1-234 abcd False
0123-4 True

This has the bonus of being easier to modify in the future.

Upvotes: 0

Hambone
Hambone

Reputation: 16377

You certainly can do this through just Regex, however, I always have this lingering fear of creating code that either:

1) only I understand or remember 2) even I don't understand when looking back

In that spirit, it seems if you do a simple split, your string might be easier to evaluate:

string[] parts = agencia.Split('-');
if ((parts.Length == 1 && Regex.IsMatch(agencia, @"^\d{1,4}$")) ||
    (parts.Length == 2 && Regex.IsMatch(parts[0], @"^\d{1,4}$")) && 
        Regex.IsMatch(parts[1], @"^[0-9X]$"))
{

}

-- EDIT --

I can't tell if you want 0 or not, so if you don't, change \d from to [1-9].

Upvotes: 0

Related Questions