## 2 replies

Last post May 06, 2019 10:48 AM by AddWeb Solution

• ### Reg Ex Help

Hi All,

Need one urgent help on Reg ex, need to identify the numeric digit with 8 digit only. but it will be allowing dash or Space. Dash and Space is totaly optional.

So valid one are

--> 12347894 --> 1010-2020 --> 1 2 3 5 4 7 8 4 --> 1 2 3 0 - 1 2 3 4

Its working with the reg ex I am using but my reg ex also identifying number with 10 digit. :( .

Please help here, requirement is it should only identify given above 4 pattern but if number is '1234512345' any other than 8 digit should not.

• samwu

Participant

1890 Points

730 Posts

### Re: Reg Ex Help

Hi amoljbp482002,

You can try my regular expression to see if it meets your needs. If not, please point out the problem.

The code:

```            string str = "12347894";

string str1 = "1010-2020";

string str2 = "1 2 3 5 4 7 8 4";

string str3 = "1 2 3 0 - 1 2 3 4";

Regex regex = new Regex(@"^(\d[- ]*){7}\d\$");

bool b = regex.IsMatch(str);```

Best Regard,
Sam

MSDN Community Support
If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

Participant

790 Points

471 Posts

### Re: Reg Ex Help

Hi,  amoljbp482002

Below Code,  completely customized  As per your requirement, Kindly please use this code in your  code with very carefully its 100% give you perfect output as you want.

```if (PatternCheck(Model.pattern))
{
}```

PatternCheck Mehod Create Globally:

```public static bool PatternCheck(string strVal)
{
var first = @"^(\d{8})\$";
var second = @"^(\d{4})[-](\d{4})\$";
var third = @"^(\d{1})[ ](\d{1})[ ](\d{1})[ ](\d{1})[ ](\d{1})[ ](\d{1})[ ](\d{1})[ ](\d{1})\$";
var fourth = @"^(\d{1})[ ](\d{1})[ ](\d{1})[ ](\d{1})[ ][-][ ](\d{1})[ ](\d{1})[ ](\d{1})[ ](\d{1})\$";

bool isError = false;

if (Regex.IsMatch(strVal, first)) { isError = false; }
else if (Regex.IsMatch(strVal, second)) { isError = false; }
else if (Regex.IsMatch(strVal, third)) { isError = false; }
else if (Regex.IsMatch(strVal, fourth)) { isError = false; }
else
{
isError = true;
}
return isError;
}```

Thanks.

Ashish Jain