简体   繁体   English

查找单引号之间的所有值(忽略撇号)

[英]Find All values between single quotes (ignoring apostrophes)

hoping someone can help me as i've realisticaly sunk 12+ hours into trying to solve this problem -希望有人可以帮助我,因为我实际上已经花了 12 多个小时试图解决这个问题 -

for some odd reason a comma separated string list value within a JSON string is being deserialised from出于某种奇怪的原因,JSON 字符串中的逗号分隔字符串列表值被反序列化

'High','Low','Medium'

to the value in the an object as being:对象中的值是:

'''High'',''Low'',''Medium'''

All these extra single quotes seem to break things, so thought about somehow removing them via a regex pattern, possibly splitting into a list further and joining them with the correct amount of single quotes (one either side of a value, as it is on the incoming json string).所有这些额外的单引号似乎都会破坏事物,因此考虑以某种方式通过正则表达式模式删除它们,可能会进一步拆分为一个列表并使用正确数量的单引号将它们连接起来(值的任一侧,因为它在传入的 json 字符串)。

I thought I Would try my hand at simply extracting the values between a matching set of quotes and I had found a pattern that worked, but later found it did not (see the commented out part) and the second pattern I have there seemed to work on regex101 but I think that is just highlighting all the single quote pairs我想我会尝试简单地提取一组匹配的引号之间的值,我发现了一个有效的模式,但后来发现它没有(见注释掉的部分),我在那里的第二个模式似乎有效在regex101 上,但我认为这只是突出显示所有单引号对

//parameter.Value = Regex.Replace(parameter.Value, "/('+')/g", "'");
string[] values = Regex.Split(parameter.Value, @"/(?<![a-zA-Z])'|'(?![a-zA-Z])/g");
    
for (int j = 0; j < values.Length; j++)
    values[j] = string.Format("'{0}'", values[j]);

parameter.Value = string.Join(",", values);

I was hoping someone would be able to help me out with pointing out where I may be going wrong in my pattern?我希望有人能够帮助我指出我的模式可能出错的地方? I really have tried but that comma separated list could contain comma's and special characters in themselves (including apostrophe's) making it that bit harder.我真的尝试过,但是逗号分隔的列表本身可能包含逗号和特殊字符(包括撇号),这使它变得更难。

Any help or guidance appreciated任何帮助或指导表示赞赏

Update更新

Thanks to @Wiktor Stribiżew for pointing out an obvious lapse in thought to me, problem is resolved.感谢@Wiktor Stribiżew 向我指出一个明显的思想失误,问题已解决。 Appeared to be using wrong method along with string literal's in the pattern.似乎使用错误的方法以及模式中的字符串文字。

Other very reasonable options in the replies, so thanks to them too.回复中的其他非常合理的选项,所以也感谢他们。

Taking into account your data format, namely, no commas inside the fields, you can use考虑到您的数据格式,即字段内没有逗号,您可以使用

var result = Regex.Replace(text, @"(?<![a-zA-Z])'|'(?![a-zA-Z])", "").Split(',');

The point is that Regex.Split "breaks" the string with the matches, while Regex.Replace will replace all matches (here, I am using an empty string, so it will remove the matches) and then .Split(',') will break the result on commas.关键是Regex.Split用匹配“破坏”字符串,而Regex.Replace将替换所有匹配(这里,我使用空字符串,所以它会删除匹配)然后.Split(',')将在逗号上破坏结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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