简体   繁体   English

C#如何根据<>字符分割字符串

[英]C# how to split a string on the basis of <> character

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. 我可以在这里使用正则表达式吗?

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. 如果您的字符串以方括号开头或结尾,则必须进行“ something”检查,以避免开头或结尾出现空字符串。

Note something like "<link<link>>" will give you { "<link", "<link>", ">" } so try to make your angle brackets balance. 请注意,诸如"<link<link>>"会为您提供{ "<link", "<link>", ">" }因此请尝试使尖括号平衡。

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. 如果遇到><时想要在中间使用空字符串,我认为您需要先分割(?=<) ,然后再分割所有结果(?<=>) -我认为您无法做到一气呵成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM