正则表达式选择多个名称,避免使用单个名称

时间:2013-05-09 10:51:34

标签: c# regex

我有案子。我想从输入中选择多个乘客姓名。在这种情况下,条件是当输入只包含单个乘客名称时,请避免使用此输入字符串。

我为这种情况创建正则表达式。它适用于从输入中选择多个名称,但当我想避免输入中的单个乘客名称时,它不起作用。

我的目标是,我只想选择那些包含多个乘客姓名而非单一乘客姓名的案例。

Regex regex = new Regex(@"(\d+\.[a-zA-Z]\S(.+))", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            foreach (Match m in regex.Matches(item))
            {
                name = m.ToString();
            }

2 个答案:

答案 0 :(得分:1)

仅供参考,我的RegEx可能不是最优化的,仍在学习中。

来自“例子”:

1.ALVARADO/RITA(ADT)   2.CABELLO/LUIS CARLOS STEVE(ADT)

要提取至少一个名称,我使用以下RegEx:

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());

答案 1 :(得分:1)

使用此正则表达式可以帮助您

(2. [A-Z] \ S(+))