2016-07-16 88 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:這只是一個臨時的解決方案,直到我找到了一個正則表達式,但是我讓循環跳過了其他所有匹配。 –