I am trying to find the correct regex syntax for matching and splitting on a word that is surrounded by double brackets.
const string originalString = "I love to [[verb]] while I [[verb]].";
I tried
var arrayOfStrings = Regex.Split(originalString,@"\[\[(.+)\]\]");
But it did not work correctly. I don't know what I am doing wrong
I would like the arrayOfStrings to come out like so
arrayOfStrings[0] = "I love to "
arrayOfStrings[1] = "[[verb]]"
arrayOfStrings[2] = " while I "
arrayOfStrings[3] = "[[verb]]"
arrayOfStrings[4] = "."
To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.
A bracket expression (an expression enclosed in square brackets, "[]" ) is an RE that shall match a specific set of single characters, and may match a specific set of multi-character collating elements, based on the non-empty set of list expressions contained in the bracket expression.
The special characters are: a. ., *, [, and \ (period, asterisk, left square bracket, and backslash, respectively), which are always special, except when they appear within square brackets ([]; see 1.4 below). c. $ (dollar sign), which is special at the end of an entire RE (see 4.2 below).
For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.
I think that 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With