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.
- static void Main(string[] args) {
- 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";
- string pattern = @ "REF\*X4\*[0-9]{10}~";
- Regex rgx = new Regex(pattern);
- string replacement = "";
- string result = rgx.Replace(data, replacement);
- Console.WriteLine("data: " + data);
- Console.WriteLine("result: " + result);
- Console.ReadLine();
- }
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.
- 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.