Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the Regex to match a word wrapped in double brackets

Tags:

c#

regex

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] = "."
like image 736
Laurence Burke Avatar asked Feb 13 '13 19:02

Laurence Burke


People also ask

How do you match curly brackets in regex?

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.

What are brackets for in regex?

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.

Are brackets special characters in regex?

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).

What does the regular expression '[ a za z ]' match?

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.


1 Answers

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);
}
like image 108
Felipe Miosso Avatar answered Nov 11 '22 05:11

Felipe Miosso