2011-10-18 16 views
6

Jestem nowy z wyrażeń regularnych. Potrzebuję wyodrębnić ścieżkę z następujących linii:Regex, aby dopasować ścieżkę w C#

XXXX  c:\mypath1\test 
YYYYYYY    c:\this is other path\longer 
ZZ  c:\mypath3\file.txt 

Potrzebuję wdrożyć metodę, która zwraca ścieżkę danej linii. Pierwsza kolumna jest słowem zawierającym 1 lub więcej znaków, nigdy nie jest pusta, druga kolumna jest ścieżką. Separator może mieć 1 lub więcej spacji, jedną lub więcej zakładek lub obie. (. Jest to przy założeniu, że pierwsza kolumna nie zawiera spacje lub tabulatory)

+0

Czy dane wejściowe to pojedynczy plik lub linie? –

+0

@RoyiNamir ma znaczenie? – username

+0

tak. traktowanie linii i pliku jest różne. chyba że czytasz wiersz po linii z pliku tex, a następnie musisz zadbać o znaki końca linii itp. –

Odpowiedz

7

To brzmi dla mnie jak chcesz tylko

string[] bits = line.Split(new char[] { '\t', ' ' }, 2, 
          StringSplitOptions.RemoveEmptyEntries); 
// TODO: Check that bits really has two entries 
string path = bits[1]; 

EDIT: W wyrażeniu regularnym prawdopodobnie można po prostu zrobić:

Regex regex = new Regex(@"^[^ \t]+[ \t]+(.*)$"); 

Przykładowy kod:

using System; 
using System.Text.RegularExpressions; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] lines = 
     { 
      @"XXXX  c:\mypath1\test", 
      @"YYYYYYY    c:\this is other path\longer", 
      @"ZZ  c:\mypath3\file.txt" 
     }; 

     foreach (string line in lines) 
     { 
      Console.WriteLine(ExtractPathFromLine(line)); 
     } 
    } 

    static readonly Regex PathRegex = new Regex(@"^[^ \t]+[ \t]+(.*)$"); 

    static string ExtractPathFromLine(string line) 
    { 
     Match match = PathRegex.Match(line); 
     if (!match.Success) 
     { 
      throw new ArgumentException("Invalid line"); 
     } 
     return match.Groups[1].Value; 
    }  
} 
+0

Ścieżki mogą mieć spacje, więc drugi jest dość zły. – xanatos

+0

@Jon: Przepraszam, potrzebuję regularnego expresion ponieważ używam .NET 1.1 i nie mam dostępu do przeciążenia StringSplitOptions.RemoveEmptyEntries. Dzięki i tak! –

+0

@ DanielPeñalba: Byłoby to przydatne, aby zacząć od - wymaganie .NET 1.1 jest bardzo rzadkie w tych dniach. Dokona edycji. –

4
StringCollection resultList = new StringCollection(); 
try { 
    Regex regexObj = new Regex(@"(([a-z]:|\\\\[a-z0-9_.$]+\\[a-z0-9_.$]+)?(\\?(?:[^\\/:*?""<>|\r\n]+\\)+)[^\\/:*?""<>|\r\n]+)"); 
    Match matchResult = regexObj.Match(subjectString); 
    while (matchResult.Success) { 
     resultList.Add(matchResult.Groups[1].Value); 
     matchResult = matchResult.NextMatch(); 
    } 
} catch (ArgumentException ex) { 
    // Syntax error in the regular expression 
} 

Podział:

@" 
(       # Match the regular expression below and capture its match into backreference number 1 
    (       # Match the regular expression below and capture its match into backreference number 2 
     |        # Match either the regular expression below (attempting the next alternative only if this one fails) 
     [a-z]       # Match a single character in the range between “a” and “z” 
     :        # Match the character “:” literally 
     |        # Or match regular expression number 2 below (the entire group fails if this one fails to match) 
     \\       # Match the character “\” literally 
     \\       # Match the character “\” literally 
     [a-z0-9_.$]     # Match a single character present in the list below 
              # A character in the range between “a” and “z” 
              # A character in the range between “0” and “9” 
              # One of the characters “_.$” 
      +        # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
     \\       # Match the character “\” literally 
     [a-z0-9_.$]     # Match a single character present in the list below 
              # A character in the range between “a” and “z” 
              # A character in the range between “0” and “9” 
              # One of the characters “_.$” 
      +        # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
    )?       # Between zero and one times, as many times as possible, giving back as needed (greedy) 
    (       # Match the regular expression below and capture its match into backreference number 3 
     \\       # Match the character “\” literally 
     ?        # Between zero and one times, as many times as possible, giving back as needed (greedy) 
     (?:       # Match the regular expression below 
     [^\\/:*?""<>|\r\n]    # Match a single character NOT present in the list below 
              # A \ character 
              # One of the characters “/:*?""<>|” 
              # A carriage return character 
              # A line feed character 
      +        # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
     \\       # Match the character “\” literally 
    )+       # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
    ) 
    [^\\/:*?""<>|\r\n]    # Match a single character NOT present in the list below 
            # A \ character 
            # One of the characters “/:*?""<>|” 
            # A carriage return character 
            # A line feed character 
     +        # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
) 
" 
+1

Wygląda to na bardzo skomplikowane, aby w zasadzie uzyskać wszystko po pierwszym zestawie spacji/kart. –

+0

@JonSkeet Zgadzam się. To jest bardziej ogólne wyrażenie regularne dla ścieżki Windows. – FailedDev

+0

@FailedDev to nie działa na przykład dla "k: \ test \ test". Jeśli spróbuję przekazać ścieżkę taką jak ** \\ test \ t><* st **, będzie ona ważna. Znalazłem to wyrażenie '^ (?: [C-zC-Z] \: | \\) (\\ [a-zA-Z _ \ - \ s0-9 \.] +) +'. Poprawnie sprawdza poprawność ścieżki w mojej opinii. Znalazłem go [tutaj] (https://www.codeproject.com/Tips/216238/Regular-Expression-to-Validate-File-Path-and-Exten) – Potato

0

Regex Tester jest dobra strona do testowania regex szybko.

Regex.Matches(input, "([a-zA-Z]*:[\\[a-zA-Z0-9 .]*]*)"); 
Powiązane problemy