Replace substring of variable length from a text file

Viewed 332

consider the following string as input

(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;

I need to remove all instances of substring like reference:url,xcon.xfocus.net/XCon2010_ChenXie_EN.pdf;

but this reference: tag is of variable length. Need to search "Reference:" keyword and remove all the text till I reach the character ";".

I've used Replace function of string class but it replaces only the fixed length substring.

desired output is

(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; 
3 Answers

You could use regex to remove items:

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

I would use regex expression in this case here is some sample code put together.

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

You can try loop with Remove instead of Replace while computing the count:

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