I have a large string with the content from a document. It contain a number of merge fields, and I would like to fetch them in order to generate the value for the merge fields.
The string could be like this:
string text = "This is a test with merge fields. [First_field], [Second_field] and [Third_field]. Not to forget the [Forth_field]."
The list I would like to get out of this, would be like this:
- [First_field]
- [Second_field]
- [Third_field]
- [Forth_field]
I know it can be done in Regex, but this is definitely not my strength. I have tried with the following code, but it seems to create a single result (from the first and last brackets):
Regex.Matches(text, @"\[.*\]", RegexOptions.IgnoreCase);
You are matching every character between
[and]. That includes], meaning you swallow every field. What you need is called lazy matching that can be done using a?after the quantifier:Alternatively, you could just match any character except
], which is done using the negation of a character class[^]