鉴于:
string command = "<CP1><SSA1>";
string command_2 = "<CP1><MPS>";
如何从命令中的“ SSA1”中获取单词“ CP1”和“ 1”,而对于command_2,则如何将其设置为“ CP1”和“ MPS”?
我已经搜索了类似的问题,但仍未找到最佳答案。
对于命令变量,我想从CP1中获取“ CP1”,并从SSA1中获取“ 1”。对于command_2变量,我想从CP1获得“ CP1”,从MPS获得“ MPS”。
您只需要在尖括号之间插入字符串即可。然后,您只需替换"SSA"
为""
,便拥有了所有想要的单词!
using System.IO;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class Program
{
static void Main()
{
string command = "<CP1><SSA1>";
string command_2 = "<CP1><MPS>";
prnt(command);
prnt(command_2);
//prnt(command+command_2); //even this will work :)
}
private static void prnt(string str)
{
List<string> l = ExtractFromString(str,"<",">");
foreach(string ll in l)
Console.WriteLine(ll.Replace("SSA",""));
}
private static List<string> ExtractFromString(string text, string start, string end)
{
List<string> Matched = new List<string>();
int index_start = 0, index_end=0;
bool exit = false;
while(!exit)
{
index_start = text.IndexOf(start);
index_end = text.IndexOf(end);
if (index_start != -1 && index_end != -1)
{
Matched.Add(text.Substring(index_start + start.Length, index_end - index_start - start.Length));
text = text.Substring(index_end + end.Length);
}
else
exit = true;
}
return Matched;
}
}
CP1
1
CP1
MPS
提取方法的来源:提取两个字符串之间的所有字符串
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句