C# .NET - find words on start and end characters.

Asked By shah zeb on 08-Jan-12 01:38 AM
I need a regular expression which should find words in a string on the start and end characters
in my case i am using '$' as my start characters and "|" as my ending characters

e.g: $egg| $head| $cafe|
should be displayed
kalpana aparnathi replied to shah zeb on 08-Jan-12 05:04 AM
string s = "$edd|$head|";
foreach (Match match in Regex.Matches(s, @"(?<!\w)$\w+|"))
kalpana aparnathi replied to shah zeb on 08-Jan-12 05:07 AM
Try this forget first one :

string input = "$edd| $head| $cafe|";
foreach (Match match in Regex.Matches(input, "(\\$\\w+)|"))

shah zeb replied to kalpana aparnathi on 08-Jan-12 05:15 AM
both of them not working
i just found a solution

string input = "$edd| $head| $cafe|";

Regex _regex = new Regex(@"(?<=\[)(.*?)(?=\])");
MatchCollection collection = _regex.Matches(input);
foreach (Match m in collection)
dipa ahuja replied to shah zeb on 08-Jan-12 06:05 AM
You can use simply substring function

protected void Page_Load(object sender, EventArgs e)
    string input = "OneTwoThree";
    // B
    // The regular expression we use to match
    Regex r1 = new Regex(@"One([A-Za-z0-9\-]+)Three");
    // C
    // Match the input and write results
    Match match = r1.Match(input);
    if (match.Success)
      string v = match.Groups[1].Value;

Output : two

But here you cannot use the symbol $ because its used as a pattern in ragular expression

if you want for symbols then you have to use the substring function

string s = "$egg| $head| $cafe|";
Response.Write(s.Substring(s.IndexOf('$')+1, s.IndexOf('|')));