[RESOLVED] Regular Expression Help
Hi, i'm having some problems with regualr expressions,
how can i write a regualr expression so that the following string
Code:
strInput = "Hello:World";
strMatch = @"[^:]*:";
foreach(System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(strInput,strMatch))
{
Console.WriteLine(m.Value);
}
it provides two matches 'Hello' and 'World'
Thanks
Rohan
Re: Regular Expression Help
Are you sure you want to do it with regular expressions? I would do it with the split function.
Code:
String[] seperators = new String[1];
seperators[0] = ":";
String[] results = strInput.Split(seperators);
I usually do a Trim() before and after to remove spaces before and after the text. And there are also some interesting parameters like this one:
Code:
Split(seperators, StringSplitOptions.RemoveEmptyEntries)
This for cases like "sometext::sometext2".
I hope this helps. Ofcourse if this makes part of something bigger and more complicated, I can see why you want to use regular expressions anyway. But remember regular expressions are heavy on the processor.
Re: Regular Expression Help
Oh and if you want to display them:
Code:
foreach (String s in results){
Console.Writeline(s);
}
or
Code:
for(int i=0;i<results.Length;i++){
Console.Writeline(s[i]);
}
But I guess you know that :) But just to make it complete
Re: Regular Expression Help
Hi thanks for the reply,
I was trying to combine it with another regular expression, i have worked out how to do it now... here is the whole thing
Code:
string strInput = @"[Resource:Name]\MyDirectory\[Demo:Application].exe";
string strMatch = @"(?<PlaceHolder>\[(?<Resource>[^\:]*):(?<Key>[^\]]*)[\]])";
foreach(System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(strInput,strMatch))
{
Console.WriteLine(m.Groups["PlaceHolder"].Value);
Console.WriteLine(m.Groups["Resource"].Value);
Console.WriteLine(m.Groups["Key"].Value);
}
This outputs
[Resource:Name]
Resource
Name
[Demo:Application]
Demo
Application
By using these groups i can look up the required resource and replace the 'PlaceHolder' in the original string
Thanks
Rohan