2011-10-18 24 views
6

Sono nuovo con espressioni regolari. Ho bisogno di estrarre il percorso dalle seguenti linee:Regex per abbinare un percorso in C#

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

Ho bisogno di attuare un metodo che restituisce il percorso di una data linea. La prima colonna è una parola con 1 o più caratteri, mai vuota, la seconda colonna è il percorso. Il separatore potrebbe essere 1 o più spazi o una o più schede o entrambe. (. Ciò presuppone che la prima colonna non contiene spazi o schede)

+0

l'input è un file o righe singolarmente? –

+0

@RoyiNamir importa? – username

+0

sì. il trattamento per linea e per file è diverso. a meno che non lo leggi riga per riga dal file tex e poi dovrai occuparti anche dei caratteri di interruzioni di riga, ecc. –

risposta

7

Sembra a me come si vuole solo

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

EDIT: Come un'espressione regolare probabilmente si può fare solo:

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

codice di esempio:

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

I percorsi possono avere spazi, quindi il secondo è piuttosto scadente. – xanatos

+0

@Jon: Siamo spiacenti, ho bisogno di un'espressione regolare poiché utilizzo .NET 1.1 e non ho accesso a overload StringSplitOptions.RemoveEmptyEntries. Grazie comunque! –

+0

@ DanielPeñalba: Sarebbe stato utile dirlo per iniziare - richiedendo .NET 1.1 è molto raro in questi giorni. Modificherà. –

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 
} 

Ripartizione:

@" 
(       # 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

Sembra molto complicato ottenere praticamente tutto dopo il primo set di spazi/tabulazioni. –

+0

@JonSkeet Sono d'accordo. Questa è un'espressione regolare più generale per il percorso di Windows. – FailedDev

+0

@FailedDev non funziona, ad esempio, per "k: \ test \ test". Se provo a passare il percorso come ** \\ test \ t><* st ** sarà valido. Ho trovato questo regex '^ (?: [C-zC-Z] \: | \\) (\\ [a-zA-Z _ \ - \ s0-9 \.] +) +'. Convalida il percorso correttamente secondo me. Trovato [qui] (https://www.codeproject.com/Tips/216238/Regular-Expression-to-Validate-File-Path-and-Exten) – Potato

0

Regex Tester è un buon sito web per testare la Regex veloce.

Regex.Matches(input, "([a-zA-Z]*:[\\[a-zA-Z0-9 .]*]*)"); 
Problemi correlati