Rakesh
Rakesh

Reputation: 313

Regular Expression Issue while retrieving from database table

We have regular expression value @"^[a-zA-Z0-9_]*$ in database table for nvarchar column . When we are retrieving expression from database table than we are getting expression value with special char like @"^[a-zA-Z0-9_]*$"

This value is not evaluated . How I can ensure

This is the code:

public static bool IsMatch(string target, string pattern, RegexOptions options) {
    if (String.IsNullOrEmpty(target)) {
        throw new ArgumentNullException("target");
    } if (String.IsNullOrEmpty(pattern)) {
        throw new ArgumentNullException("pattern");
    }
    return Regex.IsMatch(target, pattern, options);
}

Upvotes: 1

Views: 651

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626920

In order to check if the regular expression is a valid regular expression, use ArgumentException

try
{
    var rxnew = new Regex(@"[z-a]");
}
catch (ArgumentException ae)
{
    MessageBox.Show(ae.Message);
    // Shows "parsing "[z-a]" - [x-y] range in reverse order."
}

You can unescape the " symbol by runing this S&R:

var str = "@\\\"^[a-zA-Z0-9_]$"; // Input: @\"^[a-zA-Z0-9_]$
var fixed_str = Regex.Replace(str, "(?<!\\\\)\\\\\"","\""); // Output: @"^[a-zA-Z0-9_]$

Upvotes: 1

Related Questions