Replace Custom String To Blank String From A Long String

In this post, we will find the custom string from a long string and replace it with a blank string.

To do it we use Regex object.
  1. static void Main(string[] args) {  
  2.     string data = "Indicates whether REF*X4*1346645652~ the specified regular" + "expression finds a match in the specified input string." + "Indicates whether REF*X4*1346645645~ the specified regular" + "expression finds";  
  3.     string pattern = @ "REF\*X4\*[0-9]{10}~";  
  4.     Regex rgx = new Regex(pattern);  
  5.     string replacement = "";  
  6.     string result = rgx.Replace(data, replacement);  
  7.     Console.WriteLine("data: " + data);  
  8.     Console.WriteLine("result: " + result);  
  9.     Console.ReadLine();  
  10. }  
In line 2 input data in place of a hard-coded input string. In place of it, you can read input string from text file.
  1. stringpattern=@"REF\*X4\*[0-9]{10}~";  
Pattern string is defined as,
  • =>First three characters of string are 'REF'
  • =>Then '*' follow by 'X4' and then '*'. To use '*' in Pattern use escape charcater 
  • =>Next we have 10 digit number from 0-9
  • =>At last we have '~' character
In line 4 we create Regex object using pattern.

In line 5, we define replacement string.

In line 6 we use Replace function of Regular Expression to replace the custom string from a long string and replace it with a blank string.

Replace function will take two parameters as input: one parameter as an input string and second is Regular Expression.

I hope you find my posts useful - thanks for reading and happy coding! Suggestions are welcome.