2016-07-16 48 views
0

我有一个字符串,它看起来像这里面的:C#字符串函数来得到字符两个符号

My name is **name**, and I am **0** years old. 

我需要提取的字符/秒2个星号**GETTHISVALUE** 内并将其保存到一个List<string>。什么是最好的方式来做到这一点?我更喜欢内置的c#函数或LINQ。上述例子的输出必须是:

string[0] = "name" 
string[1] = "0" 

编辑:我想提一提的是里面的值**,只能是 字母和数字,并没有空格要么。

回答

2

使用正则表达式。

var reg = new Regex(@"\*\*([a-z0-9]+)\*\*", RegexOptions.IgnoreCase); 
var matches = reg.Matches(input); 

var l = new List<string>(); 
foreach (Match m in matches) 
    l.Add(m.Groups[1].Value); 
+0

您的解决方案只生产** ** 1输出:' “名”' – khlr

+0

注意您的解决方案只匹配小写字母_(仅限字母)_。您应该执行'[A-Za-z]'或指定'IgnoreCase'选项。 –

+0

这种模式呢? '\ * \ *(。*?)\ * \ *'。产生想要的2个输出。 – khlr

2

我会用一个Regex

List<string> myList = new List<string>(); 
MatchCollection matches = Regex.Matches(<input string here>, @"(?<=\*\*)[A-Za-z0-9]+(?=\*\*)"); 

for (int i = 0; i < matches.Count; i ++) 
{ 
    if (i != 0 && i % 2 != 0) continue; //Only match uneven indexes. 
    myList.Add(matches[i].Value); 
} 

模式说明:

(?<=\*\*)[^\*](?=\*\*) 

(?<=\*\*)  The match must be preceded by two asterisks. 
[A-Za-z0-9]+ Match any combination of letters or numbers (case insensitive). 
(?=\*\*)  The match must be followed by two asterisks. 
+0

您的解决方案将产生以下** 3 **输出大写字母:'“名”''”,我‘'和'’0" ' – khlr

+0

@khlr:你是对的...我会研究它。虽然不会有答案? –

+0

@khlr:这只是一个临时的解决方案,直到我找到了一个正则表达式,但是我让循环跳过了其他所有匹配。 –