在标签上显示字符串的某些部分

本文关键字:些部 字符串 标签 显示 | 更新日期: 2023-09-27 17:56:39

输入 1

字符串 str=" 1 考沙尔·杜塔 46 母头 WL 19 WL 2";

输入 2

字符串 str1= "1 AYAN PAL 38 公头 CNF S5 49 (LB) CNF S5 49 (LB)";

如果用户输入字符串 str,我有两种不同类型的字符串,则输出应该是 (WL 2),如果用户输入字符串 str1,则输出应该是 (CNF S5 49 (LB))

所有值都是动态的,除了(WL (数字)) (CNF (1 字母 1 或 2 个数字)编号 (LB))

在标签上显示字符串的某些部分

如果您使用一些分隔符框定输入字符串,那么您可以轻松地拆分字符串,并将其存储在某个数组中并继续。

例如,将字符串框定为

字符串 str="1@KAUSHAL DUTTA@46@Female@WL 19@WL 2";

在此之后拆分字符串,例如

字符串[] str1 = str。拆分('@');

从 str1

数组中,你可以取最后一个值 str1[5]

您可以使用正则表达式:https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx

//This is the pattern for the first case WL followed by a one or more (+) digits ('d) 
//followed by any number of characters (.*) 
//the parenthesis is to us to be able to group what is inside, for further processing
string pattern1 = @"WL 'd+ (.*)";
//Pattern for the second match: CNF followed by a letter ('w) followed by one or two ({1,2}) 
//digits ('d) followed by one or more (+) digits ('d), followed by (LB) "'(LB')" 
//the backslach is to get the litteral parenthesis
//followed by any number of characters (.*)
//the parenthesis is to us to be able to group what is inside, for further processing
string pattern2 = @"CNF 'w'd{1,2} 'd+ '(LB') (.*)";
string result="";
if (Regex.IsMatch(inputString, pattern1))
{
    //Groups[0] is the entire match, Groups[1] is the content of the first parenthesis
    result = Regex.Match(inputString, pattern1).Groups[1].Value;
}
else if (Regex.IsMatch(inputString, pattern2))
{
    //Groups[0] is the entire match, Groups[1] is the content of the first parenthesis
    result = Regex.Match(inputString, pattern2).Groups[1].Value;
}