2

I have following pattern {(.*?)} and it matchs 1 item only.

How I can match multiple items in C# from this text

akjsd{OrderNumber} aksjd {PatientName} aksjak sdj askdj {PatientSurname} askdjh askdj {PatientNumber} aksjd aksjd aksjd kajsd kasjd

to get list like

{OrderNumber}

{PatientName}

{PatientSurname}

{PatientNumber}

Thank you!

Qantas 94 Heavy
  • 15,410
  • 31
  • 63
  • 82
NoWar
  • 34,755
  • 78
  • 302
  • 475

2 Answers2

4

Something like this perhaps?

string input = "akjsd{OrderNumber} aksjd {PatientName} aksjak sdj askdj {PatientSurname} askdjh askdj {PatientNumber} aksjd aksjd aksjd kajsd kasjd";
MatchCollection matches = Regex.Matches(input, "{(.*?)}");

foreach(Match match in matches)
{
    Console.WriteLine(match.Value);
}
TheQ
  • 6,630
  • 4
  • 34
  • 53
3

Use this regex {[^}]*} (more efficient because .*? backtracks at each step) and do it like this:

var resultList = new StringCollection();
var myRegex = new Regex("{[^}]*}", RegexOptions.Multiline);
Match matchResult = myRegex.Match(yourString);
while (matchResult.Success) {
    resultList.Add(matchResult.Value);
    Console.WriteLine(matchResult.Value);
    matchResult = matchResult.NextMatch();
    } 
zx81
  • 39,708
  • 9
  • 81
  • 104