特定模式字符串的正则表达式

时间:2017-09-27 05:48:20

标签: c# regex

我想从下面使用正则表达式删除特定字符串:

输入字符串:

  

{“t”:1,“i”:“a32dffdd-c99d-4df5-9296-9ae5fb024dc1”,“p”:“在DB服务器时间:星期三2017年9月27日05:27:18 GMT + 0000(UTC ),你发了这条消息:{'t':1,'i':'a32dffdd-c99d-4df5-9296-9ae5fb024dc1','p':{'你':'/ test / delayed','v': 'GET', 'H':{ 'X-BH-AGENTID': 'testagent', 'X-BH-TempToken': 'testagenttemptoken'}, 'p': '', 'T':{ 'T': 1000}}}“}

使用正则表达式删除下面的字符串:

At DB Server Time: Wed Sep 27 2017 05:27:18 GMT+0000 (UTC), you sent this message:

我想要低于输出:

  

{“t”:1,“i”:“a32dffdd-c99d-4df5-9296-9ae5fb024dc1”,“p”:“{'t':1,'i':'a32dffdd-c99d-4df5-9296 -9ae5fb024dc1' , 'p':{ 'U': '/测试/延迟', 'v': 'GET', 'H':{ 'X-BH-AGENTID': 'testagent','X-BH- TempToken ':' testagenttemptoken '},' p ':'”, 'T':{ 'T':1000}}}“}

感谢高级

3 个答案:

答案 0 :(得分:2)

我认为你可以使用这样的代码:

var input = @"{""t"":1,""i"":""a32dffdd-c99d-4df5-9296-9ae5fb024dc1"",""p"":""At DB Server Time: Wed Sep 27 2017 05:27:18 GMT+0000 (UTC), you sent this message: {'t':1,'i':'a32dffdd-c99d-4df5-9296-9ae5fb024dc1','p':{'u':'/test/delayed','v':'GET','h':{'X-BH-AgentID':'testagent','X-BH-TempToken':'testagenttemptoken'},'p':'','t':{'t':1000}}}""}";
var pattern = @"At\s+DB\s+Server\s+Time:\s+\w{3}\s+\w{3}\s+\d+\s+\d{4}\s+[0-9:]{8}\s+GMT\+\d+\s+\(UTC\)\s*,\s+you\s+sent\s+this\s+message:";
var result = Regex.Replace(input, pattern, string.Empty);

<强> C# Demo

答案 1 :(得分:1)

您可以这样做:

var input = @"{""t"":1,""i"":""a32dffdd-c99d-4df5-9296-9ae5fb024dc1"",""p"":""At DB Server Time: Wed Sep 27 2017 05:27:18 GMT+0000 (UTC), you sent this message: {\""t\"":1,\""i\"":\""a32dffdd-c99d-4df5-9296-9ae5fb024dc1\"",\""p\"":{\""u\"":\""/test/delayed\"",\""v\"":\""GET\"",\""h\"":{\""X-BH-AgentID\"":\""testagent\"",\""X-BH-TempToken\"":\""testagenttemptoken\""},\""p\"":\""\"",\""t\"":{\""t\"":1000}}}""}";

var pattern = @"""At.*message:";
var replacement = string.Empty;

var rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

你可以在那里找到一份文件:link to docs.microsoft.com 基本上,您可以用任何内容替换要删除的字符串。

但请记住:至少尝试做一些事情,而不是下次要求其他人为你编码:)

答案 2 :(得分:0)

我认为这是使用双引号中的第一个p

的最佳方法
            string input = "{\"t\":1,\"i\":\"a32dffdd-c99d-4df5-9296-9ae5fb024dc1\",\"p\":\"At DB Server Time: Wed Sep 27 2017 05:27:18 GMT+0000 (UTC), you sent this message: {'t':1,'i':'a32dffdd-c99d-4df5-9296-9ae5fb024dc1','p':{'u':'/test/delayed','v':'GET','h':{'X-BH-AgentID':'testagent','X-BH-TempToken':'testagenttemptoken'},'p':'','t':{'t':1000}}}\"}";
            string pattern = "\"p\":[^\\{]+";
            string mat = Regex.Match(input, pattern).Value;
            input = Regex.Replace(input,pattern,"\"p\": ");