2013-05-09 67 views
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

你能告訴我們你輸入的一些例子嗎? – Maloric 2013-05-09 10:55:15

+0

我想它是'1.乘客一,一些信息,2.Pessange二,其他一些信息,......'。是嗎? – 2013-05-09 10:59:28

+0

@ Maloric ..我正在粘貼一個鏈接。它包含兩個輸入字符串。一個字符串包含多個名稱,另一個字符串只包含一個名稱.http://pastebin.com/9DLhxzUp – 2013-05-09 11:01:31

回答

1

使用這個表達式它會幫助你

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

+0

謝謝它的工作。 – 2013-05-09 13:50:23

+0

我的快樂伴侶 – amitesh 2013-05-09 13:50:49

1

僅供參考,我的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());