Replace a string Using Regular Expression
HI ,
Since i am very new to regular expression
can anyone explaing how to replace a string in an INPUT String using Regular Expression
my pattern of replacing is as below
the numeric characters (0-9) present in an input string must be replaced as ","prefixed and suffixed with the characters
ex: if the input string is ABC1234DEF
then the output string after replacement should be ABC,1234,DEF
Thanks in Advance
hey,
I did something similar to this not so long ago. Unfortunately I've not got the code to hand and I haven't got around to typing it up for my blog, so I'll give you some pointers and ideas and hopefully you can get it working from that.
You should download a program called the Regulator. This is a free program that helps you create and test regular expressions. You can enter in a test string and check what the regular expression you create matches in the string. Once you get the right results you've got your regular expression.
When it comes to .NET the regular expression classes are in System.Text.RegularExpressions namespace. You'll want to use RegExp class and Match class. RegExp stores your pattern and lets you find pattern matches, the Match class stores information about pattern matches.
Look up 'Regular Expression Classes' at the MSDN library or in .NET Visual Studio help search. There is good information there telling you how to use the classes.
Once you find a match (check Match.Success) you can use Match.Index property to find where in the string you want to insert the comma. Then you use String functions to insert the comma.
In VB.NET:
Imports System.Text.RegularExpressions
Dim input As String = "ABC1234DEF"
Dim result As String = Regex.Replace(input, "(\d+)", ",$1,")
In C#:
using System.Text.RegularExpressions;
string input = @"ABC1234DEF";
string result = Regex.Replace(input, "(\d+)", ",$1,");
That should do it. Trim the last comma in case the last character is also a digit.
hope that helps,
Imran.