0

I want to split my text by <> characters.
Example suppose I have a string

 string Name="this <link> is my <name>";

Now I want to split this so that I have a array of string like

ar[0]="this "
ar[1]="<link>"
ar[2]=" is my "
ar[3]="<name>"

I was trying with split function like

string[] ar=Name.Split('<');

I have also tried

 string[] nameArray = Regex.Split(name, "<[^<]+>");

But this is not giving me

 "<link>"
 and "<name>"

But it is not a good approach.
Can I use regular expression here.

शेखर
  • 17,412
  • 13
  • 61
  • 117

1 Answers1

8

This

Regex r = new Regex(@"(?<=.)(?=<)|(?<=>)(?=.)");
foreach (var s in r.Split("this_<link>_is_my_<name>"))
{
    Console.WriteLine(s);
}

gives

this_
<link>
_is_my_
<name>

(underscores used for clarity)

The regex splits on a zero-width point (so it doesn't remove anything) which is either:

  • preceeded by something and followed by <
  • preceeded by > and followed by something

The "something" checks are necessary to avoid empty strings at the start or end if your string starts or ends with something in brackets.

Note something like "<link<link>>" will give you { "<link", "<link>", ">" } so try to make your angle brackets balance.

If you want empty strings if the string starts with < or ends with > you can use (?=<)|(?<=>). If you want empty strings in the middle when you encounter ><, I think you need to first split on (?=<) and then split all the results on (?<=>) - I don't think you can do it in one go.

Rawling
  • 49,248
  • 7
  • 89
  • 127
  • thanks for the solution but you have modified from "(?=<)|(?<=>)" to (?<=.)(?=<)|(?<=>)(?=.) why previous too was working? – शेखर Nov 20 '12 at 10:48
  • @krshekhar That was to avoid empty strings at the start and end if your string starts or ends with angle-brackets. If you don't care about this - or want such strings - the first version should be fine. IF you want an empty string in between `><` I'm not sure how to achieve that. – Rawling Nov 20 '12 at 10:50
  • @downvoter Care to comment? As far as I can tell, this works. If there's a situation where it doesn't work, tell me. – Rawling Nov 21 '12 at 10:41