What will the regular expression be for matching a word enclosed in double brackets

I am trying to find the correct regular expression syntax for matching and parsing a word surrounded by double brackets.

const string originalString = "I love to [[verb]] while I [[verb]].";

I tried

var arrayOfStrings = Regex.Split(originalString,@"\[\[(.+)\]\]");

But that did not work. I do not know what I am doing wrong.

I would like arrayOfStrings to look like this:

arrayOfStrings[0] = "I love to "
arrayOfStrings[1] = "[[verb]]"
arrayOfStrings[2] = " while I "
arrayOfStrings[3] = "[[verb]]"
arrayOfStrings[4] = "."
+5
source share
2 answers

I think this is what you need.

string input = "I love to [[verb]] while I [[verb]].";
string pattern = @"(\[\[.+?\]\])";

string[] matches = Regex.Split( input, pattern );

foreach (string match in matches)
{
    Console.WriteLine(match);
}
+8
source

The answer, which will produce exactly what you want @"(?=\[\[.*?\]\])|(?<=\]\])".

It has two parts to it, separated by a |"or" symbol .

(?=\[\[.*?\]\]) , [[ ]], [.

(?<=\]\]) , ]] ].

"lookahead" "lookbehind", .

+3

All Articles