C#String用于获取两个符号内的字符的函数

时间:2016-07-16 10:18:10

标签: c# string linq

我有一个看起来像这样的字符串:

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

我需要在2个星号**GETTHISVALUE**中提取字符 并将其保存到List<string>。最好的方法是什么?我更喜欢内置的c#函数或LINQ。上例的输出必须是:

string[0] = "name"
string[1] = "0"
编辑:我想提一下**里面的值,只能是 字母和数字也没有空格。

2 个答案:

答案 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);

答案 1 :(得分: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.