仅供参考,我的 RegEx 可能不是最优化的,仍在学习中。
来自“示例”,即:
1.ALVARADO/RITA(ADT) 2.CABELLO/LUIS CARLOS STEVE(ADT)
为了提取至少一个名称,我使用了以下正则表达式:
Regex regex = new Regex(@"(\d+\.\w+/\w+(( \w+)+)?\(\w+\))");
要提取多个名称(两个或多个),我使用了以下 RegEx:
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());