Output
Trying to match pattern: '(.*?)change:(.*?):change(.*?)' >>> begin >>> Match:'sometextchange:THIS IS A TEST:change': Group[0]: 'sometextchange:THIS IS A TEST:change' Group[1]: 'sometext' Group[2]: 'THIS IS A TEST' Group[3]: '' <<< end <<< Trying to match pattern: 'change:(.*?):change' >>> begin >>> Match:'change:THIS IS A TEST:change': Group[0]: 'change:THIS IS A TEST:change' Group[1]: 'THIS IS A TEST' <<< end <<<
of this code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace SimpleCSConsole
{
class Program
{
void WriteMatches(IEnumerable<Match> matches)
{
Console.WriteLine(">>> begin >>>");
foreach (var match in matches)
{
Console.WriteLine($"Match:'{match}':");
int index = 0;
foreach (Group group in match.Groups)
{
Console.WriteLine($"Group[{index}]: '{group.Value}'");
index++;
}
}
Console.WriteLine("<<< end <<<");
}
IEnumerable<Match> GetMatches(string input, string pattern)
{
Console.WriteLine($"Trying to match pattern: '{pattern}'");
return Regex.Matches(input, pattern, RegexOptions.Singleline).Cast<Match>();
}
void Run()
{
string myString1 = "change:";
string myString2 = ":change";
string myText = "sometextchange:THIS IS A TEST:changesometext";
var pattern1 = "(.*?)" + myString1 + "(.*?)" + myString2 + "(.*?)";
var pattern2 = $"" + myString1 + "(.*?)" + myString2;
WriteMatches(GetMatches(myText, pattern1));
WriteMatches(GetMatches(myText, pattern2));
}
static void Main()
{
new Program().Run();
Console.ReadKey();
}
}
}
If you were using group[1] with your other search pattern, you would have gotten "sometext", not "THIS IS A TEST".

New Topic/Question
Reply



MultiQuote

|