简体   繁体   English

正则表达式替换匹配

[英]Regex.Replace matching

I'm having some issues with a Json deserializer. 我在使用Json解串器时遇到一些问题。 One of the values in the returned Json is to large and is throwing exceptions. 返回的Json中的值之一很大,并引发异常。 I actually do not need the info that it is returning so I want to ignore it. 实际上,我不需要返回的信息,因此我想忽略它。 I figured the best way to do this would be to search the json string for the attribute, then set the value to null. 我想最好的方法是在json字符串中搜索属性,然后将值设置为null。

Here's a sample of the returned Json that is giving me the error. 这是给我错误的返回Json的样本。

           "attributes": [
                {
                    "defindex": 143,
                    "value": 2111522248,
                    "float_value": 364329070052570260000000000000
                },

I would like to replace the "float_value" attribute(Ie. 36432907005257026000000000 ) with an empty value, or nill, so that it does not throw the exception during Json Deserialization. 我想将“ float_value”属性(即36432907005257026000000000 )替换为空值或nill,以便在Json反序列化期间不引发异常。

I'm using Regex.Replace(json, "\\"float_value\\": \\\\d+", String.Empty); 我正在使用Regex.Replace(json, "\\"float_value\\": \\\\d+", String.Empty);

But it doesn't appear to be removing it, and is still throwing the exception. 但是它似乎并没有将其删除,并且仍在引发异常。

When you say \\\\d+ you're actually escaping the second \\ , and not indicating that you want a \\d . 当您说 \\\\d+ ,实际上是在转义第二个 \\ ,而不是表示您想要 \\d Try this instead: 尝试以下方法:

 
 
 
  
  Regex.Replace(json, "\\"float_value\\": \\d+", String.Empty);
 
  

Here's a breakdown of what you had before. 这是您以前拥有的细分。 Note the literal d : http://www.regex101.com/r/wQ6jD5 请注意文字 dhttp : //www.regex101.com/r/wQ6jD5

Edit: Nvm, this doesn't apply since you were using a normal string rather than a verbatim string. 编辑:Nvm,这不适用,因为您使用的是普通字符串而不是逐字字符串。 As Jj' indicated, I think the problem is that you have a , on the previous line which you didn't remove. 随着JJ”表示,我认为这个问题是你有一个,比上线,你没有删除。

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

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