我有一个正则表达式模式数组,以类似 JSON 的格式存储在数据库的单个字段中。这是一个示例:
["^.*\/Car($|\/$|\?|\/\?)"]
我正在尝试获取此值并使用 Newtonsoft.Json 将其转换为
string[]
对象。每当我尝试反序列化字符串时,它都会抛出一个 Newtonsoft.Json.JsonReaderExeption
。
这是我尝试使用的代码:
public static void Main(string[] args)
{
//working example
string patterns = @"[""^.*\/Car""]";
var x = JsonConvert.DeserializeObject<string[]>(patterns);
Console.WriteLine(x.First()); //outputs ^.*/Car
//non-working example
patterns = @"[""^.*\/Car\?""]";
x = JsonConvert.DeserializeObject<string[]>(patterns); //throws Newtonsoft.Json.JsonReaderException: 'Bad JSON escape sequence: \?. Path '', line 1, position 12.'
Console.WriteLine(x.First());
//non-working example
patterns = @"[""^.*\/Car\?""]"; //actually redundant
x = JsonConvert.DeserializeObject<string[]>(JsonEncodedText.Encode(patterns).ToString()); //throws Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: \. Path '', line 1, position 2.'
Console.WriteLine(x.First());
//working example
patterns = @"[""^.*\/Car\\?""]";
x = JsonConvert.DeserializeObject<string[]>(patterns); //outputs .*/Car\?
Console.WriteLine(x.First());
//what I ultimately would need to work
//Regex pattern ^.*\/Car($|\/$|\?|\/\?)
patterns = @"[""^.*\/Car($|\/$|\?|\/\?)""]";
x = JsonConvert.DeserializeObject<string[]>(patterns); //throws Newtonsoft.Json.JsonReaderException
Console.WriteLine(x.First());
}
如您所见,正则表达式模式中的转义问号 (
\?
) 导致了问题。仅当我转义反斜杠 (\\?
) 时,反序列化才能按预期工作(如第四个示例中所示)。
这导致我寻找一种转义函数,但到目前为止我还没有找到任何有效的函数。我尝试使用
JsonEncodedText.Encode()
,但不幸的是这也没有帮助。在反序列化之前使用 patterns
转义 Regex.Escape(patterns)
也会抛出 Newtonsoft.Json.JsonReaderExeption
。
有人知道我需要如何转义字符串才能将其反序列化为
string[]
或 List<string>
对象吗?
我还认为模式数组可能首先没有正确存储在数据库中,但不幸的是我影响值存储方式的能力非常有限。
就在我发布问题后,我意识到当我加倍反斜杠时一切正常:
x = JsonConvert.DeserializeObject<string[]>(patterns.Replace("\\", "\\\\"));
我太蠢了 - 我真的花了几个小时在这上面。