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

时间:2019-06-14 09:18:31

标签: c# .net string replace

将以下字符串视为输入

(msg:"NTL - 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;

但此参考:标记的长度可变。需要搜索“参考:”关键字,并删除所有文本,直到到达字符“;”为止。

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

所需的输出是

(msg:"NTL - 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; 

3 个答案:

答案 0 :(得分:10)

您可以使用正则表达式删除项目:

var result = Regex.Replace(input, "reference:[^;]*;", string.Empty, RegexOptions.IgnoreCase);

答案 1 :(得分:2)

在这种情况下,我将使用正则表达式来编写一些示例代码。

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

答案 2 :(得分:1)

在计算计数时,您可以使用Remove而不是Replace尝试 loop

  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);
  }