I'm trying to design a RegEx in C# to match 4 digits and 6 characters in a string.

 string str = "Hello World! ABCD112233 fsdf sdfsdf 234324 fdsfds 4234 efwedf34ref dfsdf34f34f";

that matches only ABCD112233 in the above string.

Regex regex = new Regex("^[A-Za-z]{4}[0-9]{6}$", RegexOptions.Multiline);

How do I solve this problem?

1 Answers

Community On Best Solutions

You would use the {n} quantifier to match a certain number of characters like so: [A-Za-z]{4}[0-9]{6}. This will match 4 letters (A-Z, a-z) and then 6 digits (0-9).

Note: don't use ^ and $ at the start and end as then it will only match if the whole word matches the regex.