SKull
SKull

Reputation: 331

How can I split a regex into exact words?

I need a little help regarding Regular Expressions in C#

I have the following string

"[[Sender.Name]]\r[[Sender.AdditionalInfo]]\r[[Sender.Street]]\r[[Sender.ZipCode]] [[Sender.Location]]\r[[Sender.Country]]\r"

The string could also contain spaces and theoretically any other characters. So I really need do match the [[words]].

What I need is a text array like this

"[[Sender.Name]]",
"[[Sender.AdditionalInfo]]",
"[[Sender.Street]]",
// ... And so on. 

I'm pretty sure that this is perfectly doable with:

var stringArray = Regex.Split(line, @"\[\[+\]\]")

I'm just too stupid to find the correct Regex for the Regex.Split() call.

Anyone here that can tell me the correct Regular Expression to use in my case?

As you can tell I'm not that experienced with RegEx :)

Upvotes: 0

Views: 577

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174706

Do matching if you want to get the [[..]] block.

Regex rgx = new Regex(@"\[\[.*?\]\]");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[0].Value);

IDEONE

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

The regex you are using (\[\[+\]\]) will capture: literal [s 2 or more, then 2 literal ]s.

A regex solution is capturing all the non-[s inside doubled [ and ]s (and the string inside the brackets should not be empty, I guess?), and cast MatchCollection to a list or array (here is an example with a list):

var str = "[[Sender.Name]]\r[[Sender.AdditionalInfo]]\r[[Sender.Street]]\r[[Sender.ZipCode]] [[Sender.Location]]\r[[Sender.Country]]\r";
var rgx22 = new Regex(@"\[\[[^]]+?\]\]");
var res345 = rgx22.Matches(str).Cast<Match>().ToList();

Output:

enter image description here

Upvotes: 1

Vajura
Vajura

Reputation: 1132

Why dont you split according to "\r"?

and you dont need regex for that just use the standard string function

string[] delimiters = {@"\r"};
string[] split = line.Split(delimiters,StringSplitOptions.None);

Upvotes: 6

Related Questions