匹配并替换 [英] Match and replace

查看:77
本文介绍了匹配并替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长字符串,并且在该字符串中 ,我有以下文本:

I have a long string and within that string I have the following text:

"formatter": "SomeInformationHere"

我需要在长字符串中找到上述文本并删除双精度在 SomeInformationHere 周围加上引号,因此结果如下所示,但是必须在 formatter一词周围加上引号。

I need to find the above text within the long string and remove the double quote marks around SomeInformationHere so the result looks like the below, but the quotes around the word "formatter" must remain.

"formatter": SomeInformationHere

我尝试了以下操作,发现了字符串,但是我不确定如何仅替换值 SomeInformationHere 周围的引号:

I tried the below, which finds the string, but I'm not sure how to replace just the quotation marks around the value SomeInformationHere:

string pattern = "\"formatter\": ([\"]).*([\"])";
Match match = Regex.Match(myString, pattern, RegexOptions.IgnoreCase);
//Replace text in "myString" here
myString = ?????
//Output match value:
Response.Write(match.Value);

编辑:哦,我忘了提到上面的模式可能多次出现在 mystring中

Oh I forgot to mention that the above pattern could be in the "mystring" more than once and all will need the replacement doing on them.

编辑2:

我已经看过regex测试器站点(感谢链接),并粘贴到我的测试字符串和regex模式中,似乎可以正常工作,但是当我将相同的模式放入点网中时,替换好像在选择单行选项一样。以下是我使用的代码。

I've had a look at the regex tester site (thanks for the link) and pasted in my test string and regex pattern, it seems to work in that, but when I put the same pattern into dot net the replacement seems to work as if the "singleline" option has been selected. Below is the code I've used.


  1. 字符串-请注意,该字符串不包含任何回车符- 格式化以提高可读性。

  1. The string - note that this does NOT contain any carriage returns - it's one long string that has been built from an XML file. Formatted for readability.

{
        "chart": {
                "borderRadius": 15,
                "borderWidth": 1,
                "renderTo": "ChartContainer1",
                "type": "pie"
        },
        "credits": {
                "enabled": false
        },
        "labels": {
                "items": [{
                        "html": "Label 1",
                        "style": {
                                "left": "10px",
                                "top": "30px"
                        }
                }, {
                        "html": "Label 2",
                        "style": {
                                "left": "10px",
                                "top": "50px"
                        }
                }, {
                        "dummy": null
                }]
        },
        "plotOptions": {
                "pie": {
                        "allowPointSelect": true,
                        "cursor": "pointer",
                        "showInLegend": true
                }
        },
        "series": [{
                "data": [{
                        "name": "Firefox",
                        "y": 45.0
                }, {
                        "name": "IE",
                        "y": 26.8
                }, {
                        "name": "Chrome",
                        "selected": true,
                        "sliced": true,
                        "y": 12.8
                }, {
                        "name": "Safari",
                        "y": 8.5
                }, {
                        "name": "Opera",
                        "y": 6.2
                }, {
                        "name": "Others",
                        "y": 0.7
                }],
                "name": "Browser share"
        }, {
                "dummy": null
        }],
        "test": {
                "formatter": "function(){return \u0027\u0027+ this.point.name +\u0027<\/b>: \u0027+ this.y +\u0027 %\u0027;}"
        },
        "title": {
                "align": "center",
                "text": "Your chart title here"
        },
        "tooltip": {
                "formatter": "function(){return \u0027\u0027+ this.point.name +\u0027<\/b>: \u0027+ this.y +\u0027 %\u0027;}"
        }
}


您可以在测试和工具提示旁边的底部看到格式化程序:部分。当上面的字符串都在测试仪中的多行(带有CR)时,我当前正在使用的patten起作用,但是当我将它放在应有的一行上时,该模式将不起作用

As you can see near the bottom next to "test" and "tooltip" I have the "formatter:" part. the patten I'm currently using works when the above string is all on several lines (with CRs) in the tester, but when I put it on ONE line like it should be then the pattern doens't work

我正在使用的.NET代码/模式是:

The .NET code / pattern I'm using is:

string pattern = "(\"formatter\": )\"(.*)\"( })";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
aJSON = regex.Replace(aJSON, "$1$2$3");

再次感谢。

REGex测试器站点中的目标字符串:(不带CR)

Target string in the REGex tester site: (with no CRs)

{"chart": {"borderRadius": 15, "borderWidth": 1, "renderTo": "ChartContainer1", "type": "pie" }, "credits": {"enabled": false }, "labels": { "items": [ {"html": "Label 1", "style": {"left": "10px", "top": "30px" } }, {"html": "Label 2", "style": {"left": "10px", "top": "50px" } }, {"dummy": null } ] }, "plotOptions": {"pie": {"allowPointSelect": true, "cursor": "pointer", "showInLegend": true } }, "series": [ { "data": [ {"name": "Firefox", "y": 45.0 }, {"name": "IE", "y": 26.8 }, {"name": "Chrome", "selected": true, "sliced": true, "y": 12.8 }, {"name": "Safari", "y": 8.5 }, {"name": "Opera", "y": 6.2 }, {"name": "Others", "y": 0.7 } ], "name": "Browser share" }, {"dummy": null } ], "test": {"formatter": "function(){return \u0027\u0027+ this.point.name +\u0027<\/b>: \u0027+ this.y +\u0027 %\u0027;}" }, "title": {"align": "center", "text": "Your chart title here" }, "tooltip": {"formatter": "function(){return \u0027\u0027+ this.point.name +\u0027<\/b>: \u0027+ this.y +\u0027 %\u0027;}" } }






我现在找到了似乎有用的正确模式,并在字符串中找到了多个匹配项。


I've now found the correct pattern that seems to work and find multiple matches in the string. Posting it here for completion.


字符串模式=(\ formatter\:)\(。 [^ \] * )\;


推荐答案

其他人几乎都使用捕获组和替换来钉牢它,只是想提供更多上下文:

Everybody else has pretty much nailed it with using capturing groups and substitutions, just wanted to provide a little more context:

这里使用的主要两件事是命名捕获组替换

The main two things that are used here are Named Capturing Groups and Substitutions

static void Main(string[] args) {

    var input = new[] {
        "\"formatter\": \"John\"", 
        "\"formatter\": \"Sue\"", 
        "\"formatter\": \"Greg\""
    };

    foreach (var s in input) {
        System.Console.Write("Original: [{0}]{1}", s, Environment.NewLine);
        System.Console.Write("Replaced: [{0}]{1}", ReFormat(s), Environment.NewLine);
        System.Console.WriteLine();
    }

    System.Console.ReadKey();
}

private static String ReFormat(String str) {
    //Use named capturing groups to make life easier
    var pattern = "(?<label>\"formatter\"): ([\"])(?<tag>.*)([\"])";

    //Create a substitution pattern for the Replace method
    var replacePattern = "${label}: ${tag}";

    return Regex.Replace(str, pattern, replacePattern, RegexOptions.IgnoreCase);
}

这篇关于匹配并替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆