猿问

通过按特定标签拆分字符串来获取字符串列表

我想通过特定标签将字符串拆分为列表或数组。

<START><A>message<B>UnknownLengthOfText<BEOF><AEOF><A>message<B>UnknownLengthOfText<BEOF><AEOF><END>

我想把上面的例子分成两个项目,项目是<A><AEOF>标签之间的字符串

任何帮助表示赞赏。


qq_花开花谢_0
浏览 179回答 3
3回答

萧十郎

我会为此建议简单的正则表达式。看看这个例子:using System.Diagnostics;using System.Text.RegularExpressions;...Regex regex = new Regex("<A>(.*?)<B><BEOF>(.*?)<AEOF>");string myString = @"<START><A>message<B><BEOF>UnknownLengthOfText<AEOF><A>message<B><BEOF>some other line of text<AEOF><END>";MatchCollection matches = regex.Matches(myString);foreach (Match m in matches){&nbsp; &nbsp; Debug.WriteLine(m.Groups[1].ToString(), m.Groups[2].ToString());}编辑:由于字符串在一行中,正则表达式应该是“懒惰的”,用惰性量词标记?。此外,我更改了正则表达式,以便它也使用 sTrenat 的建议来自动解析消息和标题。所以,而不是Regex regex = new Regex("<A>(.*)<AEOF>");我用了Regex regex = new Regex("<A>(.*?)<B><BEOF>(.*?)<AEOF>");注意附加的?标记惰性量词,当它找到标签之间的第一个匹配时停止(没有?整个 strign 将被捕获,而不是n标签之间的消息)

幕布斯7119047

用这样的东西试试:string test = @"<START>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<A>message<B><BEOF>UnknownLengthOfText<AEOF>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<A>message<B><BEOF>UnknownLengthOfText<AEOF>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <END>";//for this test this will give u an array containing 3 items...string[] tmp1 = test.Split("<AEOF>");//here u will store your results inList<string> results = new List<string>();//for every single one of those 3 items:foreach(string item in tmp1){&nbsp; &nbsp; &nbsp;//this will only be true for the first and second item&nbsp; &nbsp; &nbsp;if(item.Contains("<A>"))&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string[] tmp2 = item.Split("<A>");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//As the string you are looking for is always BEHIND the <A> you&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//store the item[1], (the item[0] would be in front)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;results.Add(tmp2[1]);&nbsp; &nbsp; &nbsp;}}

qq_遁去的一_1

而不是使用 String.Split 你可以使用 Regex.Split 如下&nbsp; &nbsp; &nbsp; &nbsp; var stringToSplit = @"<START>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <A>message<B>UnknownLengthOfText<BEOF><AEOF>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <A>message<B>UnknownLengthOfText<BEOF><AEOF>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <END>";&nbsp; &nbsp; &nbsp; &nbsp; var regex = "<A>(.*)<AEOF>";&nbsp; &nbsp; &nbsp; &nbsp; var splitStrings = Regex.Split(stringToSplit, regex);splitStrings 将包含 4 个元素splitString[0] = "<START>"splitString[1] = "message<B>UnknownLengthOfText<BEOF>"splitString[2] = "message<B>UnknownLengthOfText<BEOF>"splitString[3] = "<END>"玩正则表达式只能给你和之间的字符串
随时随地看视频慕课网APP
我要回答