僅供參考,我的RegEx可能不是最優化的,仍然在學習中。
從「示例」,它是:
1.ALVARADO/RITA(ADT) 2.CABELLO/LUIS CARLOS STEVE(ADT)
要拉至少一個名稱,我使用了下面的正則表達式:
Regex regex = new Regex(@"(\d+\.\w+/\w+((\w+)+)?\(\w+\))");
要拉一個以上的名稱(其是兩個或更多),我用下面的正則表達式:
Regex regex = new Regex(@"(\d+\.\w+/\w+ \w+((\w+)+)?\(\w+\))");
然後,檢索姓和名,我做了一些字符串操作:
// Example string
string item = @"1.ALVARADO/RITA(ADT) 2.CABELLO/LUIS CARLOS STEVE(ADT)";
// Create a StringBuilder for output
StringBuilder sb = new StringBuilder();
// Create a List for holding names (first and last)
List<string> people = new List<string>();
// Regex expression for matching at least two people
Regex regex = new Regex(@"(\d+\.\w+/\w+ \w+((\w+)+)?\(\w+\))");
// Iterate through matches
foreach(Match m in regex.Matches(item)) {
//Store the match
string match = m.ToString();
// Remove the number bullet
match = match.Substring(2);
// Store location of slash, used for splitting last name and rest of string
int slashLocation = match.IndexOf('/');
// Retrieve the last name
string lastName = match.Substring(0, slashLocation);
// Retrieve all first names
List<string> firstNames = match.Substring(slashLocation + 1, match.IndexOf('(') - slashLocation -1).Split(' ').ToList();
// Push first names to List of people
firstNames.ForEach(a => people.Add(a + " " + lastName));
}
// Push list of people into a StringBuilder for output
people.ForEach(a => sb.AppendLine(a));
// Display people in a MessageBox
MessageBox.Show(sb.ToString());
你能告訴我們你輸入的一些例子嗎? – Maloric 2013-05-09 10:55:15
我想它是'1.乘客一,一些信息,2.Pessange二,其他一些信息,......'。是嗎? – 2013-05-09 10:59:28
@ Maloric ..我正在粘貼一個鏈接。它包含兩個輸入字符串。一個字符串包含多個名稱,另一個字符串只包含一個名稱.http://pastebin.com/9DLhxzUp – 2013-05-09 11:01:31