简体   繁体   中英

Regex to remove escape characters (specific ones) in C#

The regex below is not what I exactly need:

Regex.Replace(value.ToString(), "[^0-9a-zA-Z]+", "")

I need to remove escape characters from my string because I am creating one SQL with string and when I have this character ' or this \\r\\n etc. my Sql generates an error, I cannot use : SqlParameter in this case as I just have a list of SQLs in string, but I can remove the characters that I don't want.

So, I only need to remove these characters:

 \\r \\n ' /\\ 

Added my codes as requested:

private static string ConvertWhetherUsesComas(object value)
{
    // formats with comas or not
    if (value is String)
    {
        // fix problem with break characters such as \/`'
        value = String.Format("'{0}'", Regex.Replace(value.ToString(), "[^0-9a-zA-Z]+", ""));
    }
    else if (value is DateTime)
    {
        value = String.Format("'{0}'", value.SafeToDateTime(null).Value.ToString("yyyy-MM-dd hh:mm:ss tt"));
    }
    else if (value == null)
    {
        value = "NULL";
    }
    else if (value is Boolean)
    {
        value = value.SafeToBool(false) == false ? 0 : 1;
    }
    return value.ToString();
}
private static List<String> ConvertDiferencesToSql<T>(Differences<T> differences, string tableName, string primaryKey) where T : IHasId<int>
{
    var result = new List<String>();

    differences.New.ToList().ForEach(newItem =>
    {
        var fieldNames = new StringBuilder();
        var fieldValues = new StringBuilder();
        var properties = newItem.GetType().GetProperties().ToList();
        properties.ForEach(f =>
        {
            var propertyName = f.Name.ToUpper() == "ID" ? primaryKey : f.Name;
            var propertyValue = ConvertWhetherUsesComas(f.GetValue(newItem));

            if (propertyValue == "NULL") return; // ignores null values
            fieldNames.AppendFormat("{0},", propertyName);
            fieldValues.AppendFormat("{0},", propertyValue);
        });
        var sqlFields = fieldNames.ToString(0, fieldNames.Length - 1);
        var sqlValues = fieldValues.ToString(0, fieldValues.Length - 1);

        result.Add(String.Format("INSERT INTO {0} ({1}) VALUES ({2});", tableName, sqlFields, sqlValues));
    });

    differences.Changed.ForEach(changedRecord =>
    {
        var fields = new StringBuilder();

        changedRecord.ChangedFields.ForEach(changedField =>
        {
            var propertyName = changedField.Property == "ID" ? primaryKey : changedField.Property;
            var propertyValue = ConvertWhetherUsesComas(changedField.NewValue);

            fields.AppendFormat("{0}={1},", propertyName, propertyValue);
        });

        var sqlFields = fields.ToString(0, fields.Length - 1);

        result.Add(String.Format("UPDATE {0} SET {1} WHERE {2}={3};", tableName, sqlFields, primaryKey, changedRecord.Id)); 
    });

    differences.Deleted.ForEach(deletedItem => result.Add(String.Format("DELETE FROM {0} WHERE {1}={2};", tableName, primaryKey, deletedItem.GetId())));

    return result;
}

You can place these characters into a character class, and replace with string.Empty :

var rgx4 = new Regex(@"[\r\n'/\\]");
var tst = "\r \n ' /\\";
tst = rgx4.Replace(tst, string.Empty);

Result:

在此处输入图片说明

A character class usually executes faster, as with alternative list, there is a lot of back-tracking impeding performance.

If I understood correctly, you want something like this :

Regex.Replace(value.ToString(), "(\\\\n|\\\\r|'|\\/\\\\)+", "")

See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM