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

时间:2016-07-13 08:28:36

标签: c# asp.net string

输入1

  

string str =" 1 KAUSHAL DUTTA 46女WL 19 WL 2&#34 ;;

输入2

  

string str1 =" 1 AYAN PAL 38男性CNF S5 49(LB)CNF S5 49(LB)&#34 ;;

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

  

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

2 个答案:

答案 0 :(得分:0)

如果使用某个分隔符对输入字符串进行构图,则可以轻松拆分字符串,然后将其存储在某个数组中并继续。

例如,将您的字符串框架为

string str =“1 @ KAUSHAL DUTTA @ 46 @ Female @ WL 19 @ WL 2”;

在此之后将字符串拆分为

string [] str1 = str.Split('@');

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

答案 1 :(得分:0)

您可以使用正则表达式: 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;
}