Tutorial :preg_match to .NET equivalent



Question:

I have the following code in PHP:

    if (preg_match('@^[a-z0-9/._-]+$@i', $script)        && !preg_match('@([.][.])|([.]/)|(//)@', $script))  

I'm making the assumption that the predicate for the if statement returns true for the string js/core.js.

How would I translate this to C#? The dumb translation is as follows:

if(Regex.IsMatch(script,"@^[a-z0-9/._-]+$@i")     && !Regex.IsMatch(script,"@([.][.])|([.]/)|(//)@"))  

but I suspect that the @ symbol has meaning associated with it that I can't get to the bottom of. A translation to .NET regex would be nice, but I'm entirely familiar with .NET regex, so an explanation of the relevant syntax differences would suffice.

Many thanks.


Solution:1

The @s are just delimiter. You don't need them in .NET

if(Regex.IsMatch(script,"^[a-z0-9/._-]+$", RegexOptions.IgnoreCase)     && !Regex.IsMatch(script,"([.][.])|([.]/)|(//)"))  


Solution:2

The @ symbol in .net is syntactic sugar that denotes that the following string will be a literal and is located outside of the quotes. this allows for a string where you do not have to double-escape the backslash character (\). So "c:\\foo\\bar" becomes @"c:\foo\bar"


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »