papakia papakia - 1 year ago 475
Javascript Question

Convert Javascript Regex to C# Regex

I have the following JavaScript regular expression used in jQuery Validation by jzaefferer for validating UK mobile numbers:


It works a treat, however I would also like to use it in C# but do not understand how to convert this into a C# regular expression

How can this be converted into a C# regular expression and what is the C# equivalent?

Answer Source

JavaScript has literal regex syntax so your expression could be something like:

var is_mobile = /^(?:(?:(?:00\s?|\+)44\s?|0)7(?:[1345789]\d{2}|624)\s?\d{3}\s?\d{3})$/.test(someString);

In C# we can create an instance of Regex or use a static method, I prefer the latter, so try something like:

bool is_mobile = Regex.IsMatch(someString,@"^(?:(?:(?:00\s?|\+)44\s?|0)7(?:[1345789]\d{2}|624)\s?\d{3}\s?\d{3})$",RegexOptions.IgnoreCase);

Basically dropping the enclosing /. There could be some regex syntax differences as well however in this instance it translates straight across.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download