Clark Jeria
Clark Jeria

Reputation: 53

Getting regular expression from database

I Have my regex in a SQL Database

for example: ^[A-Z Ñ\s\.\,\\"\%]+$

Then, i get it with a SQL Reader

sql.Reader["Regular_Expression"].ToString()

But, that return the following: "^[A-Z Ñ\\s\\.\\,\\\\"\\%]+$"

Anyone know how to avoid the .ToString() function to change the string, like when you use @.

Upvotes: 2

Views: 1128

Answers (2)

Clark Jeria
Clark Jeria

Reputation: 53

To solve it you've to use Regex.Unescape() function from the Regex Library.

The problem is caused to a bad casting from object to string.

Upvotes: 1

Mike Dimmick
Mike Dimmick

Reputation: 9802

I think you're actually being led astray by the tools here. When you view the result in a Watch window in Visual Studio, it escapes any characters in the display in the same way as a regular quoted string, so you get doubled backslashes. If you actually output it somewhere, for example using System.Diagnostics.Debug.WriteLine, you shouldn't see the doubled backslashes.

When you access a column through SqlDataReader's indexer property, the return type is object. That's because it doesn't know at compile time what type it is. If the column is a string type (e.g. varchar), the returned object will be a SqlString structure, and you can cast that to string rather than calling ToString.

Upvotes: 1

Related Questions