从文本文件中替换变量长度的子字符串

6

请考虑以下字符串作为输入

(msg:"ACTIVEX Possible Microsoft WMI Administration Tools WEBSingleView.ocx ActiveX Buffer Overflow Attempt Function Call"; flow:to_client,established; file_data; content:"ActiveXObject"; nocase; distance:0; content:"WBEM.SingleViewCtrl.1"; nocase; distance:0; pcre:"/WBEM\x2ESingleViewCtrl\x2E1.+(AddContextRef|ReleaseContext)/smi"; reference:url,xcon.xfocus.net/XCon2010_ChenXie_EN.pdf; reference:url,wooyun.org/bug.php?action=view&id=1006; classtype:attempted-user; sid:2012157; rev:1; metadata:affected_product Windows_XP_Vista_7_8_10_Server_32_64_Bit, attack_target Client_Endpoint, deployment Perimeter, tag ActiveX, signature_severity Major, created_at 2011_01_06, updated_at 2016_07_01;

我需要删除所有类似于reference:url,xcon.xfocus.net/XCon2010_ChenXie_EN.pdf;的子字符串;

但是这个引用标签的长度是可变的。需要搜索"Reference:"关键字并删除直到字符";"的所有文本。

我已经使用了字符串类的Replace函数,但它只替换固定长度的子字符串。

期望的输出结果为

(msg:"ACTIVEX Possible Microsoft WMI Administration Tools WEBSingleView.ocx ActiveX Buffer Overflow Attempt Function Call"; flow:to_client,established; file_data; content:"ActiveXObject"; nocase; distance:0; content:"WBEM.SingleViewCtrl.1"; nocase; distance:0; pcre:"/WBEM\x2ESingleViewCtrl\x2E1.+(AddContextRef|ReleaseContext)/smi";  classtype:attempted-user; sid:2012157; rev:1; metadata:affected_product Windows_XP_Vista_7_8_10_Server_32_64_Bit, attack_target Client_Endpoint, deployment Perimeter, tag ActiveX, signature_severity Major, created_at 2011_01_06, updated_at 2016_07_01; 

你应该使用正则表达式来完成这个任务。但是如果不清楚你想要的输出结果,我们无法提供帮助。 - Roman Koliada
3个回答

10
你可以使用正则表达式来删除项目:
var result = Regex.Replace(input, "reference:[^;]*;", string.Empty, RegexOptions.IgnoreCase);

2
我会在这种情况下使用正则表达式,以下是一些示例代码。

我会在这种情况下使用正则表达式,以下是一些示例代码。

using System.Text.RegularExpressions;
string pattern = "reference\:url,[.]+?;";
string replacement= "reference:url,;";
string output = Regex.Replace(input, pattern, replacement);

1
您可以尝试在计算计数时使用Remove而不是Replaceloop结合使用。
  string input = ...;

  int start = 0;

  while (true) {
    start = input.IndexOf("reference:", start, StringComparison.OrdinalIgnoreCase);
    int stop = start >= 0 ? input.IndexOf(";", start) : -1;

    if (stop < 0)
      break;

    input = input.Remove(start, stop - start + 1);
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接