0

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

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

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

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

2 回答 2

1

仅供参考,我的 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());
于 2013-05-09T12:46:24.400 回答
1

使用这个正则表达式它会帮助你

(2.[Az]\S(.+))

于 2013-05-09T13:28:34.927 回答