2011-10-18 16 views
6

Soy nuevo con expresiones regulares. Necesito para extraer la vía de las líneas siguientes:Regex para que coincida con una ruta en C#

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

I necesidad de implementar un método que devuelve la ruta de una línea dada. La primera columna es una palabra con 1 o más caracteres, nunca está vacía, la segunda columna es la ruta. El separador podría ser de 1 o más espacios, o una o más pestañas, o ambas. (. Esto es suponiendo que la primera columna no contiene espacios o tabuladores)

+0

¿La entrada es un archivo o líneas individualmente? –

+0

@RoyiNamir ¿Importa? – username

+0

sí. el tratamiento para la línea y para el archivo es diferente. a menos que lo lea línea por línea desde el archivo tex y luego también tendrá que ocuparse de los caracteres lineales, etc. –

Respuesta

7

Me suena como si sólo quiere

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

EDIT: Como una expresión regular que probablemente sólo puede hacer:

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

código de ejemplo:

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

Las rutas pueden tener espacios, por lo que la segunda es bastante mala. – xanatos

+0

@Jon: Lo siento, necesito una expresión regular ya que estoy usando .NET 1.1 y no tengo acceso a la sobrecarga de StringSplitOptions.RemoveEmptyEntries. ¡Gracias de cualquier manera! –

+0

@ DanielPeñalba: Hubiera sido útil decirlo para empezar, ya que requerir .NET 1.1 es muy raro en estos días. Editaré –

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 
} 

Desglose:

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

Esto se ve muy complicado para obtener básicamente todo después del primer conjunto de espacios/pestañas. –

+0

@JonSkeet Estoy de acuerdo. Esa es una expresión regular más general para la ruta de Windows. – FailedDev

+0

@FailedDev no funciona, por ejemplo, para "k: \ test \ test". Si intento pasar una ruta como ** \\ test \ t><* st **, será válida. Encontré esta expresión regular '^ (?: [C-zC-Z] \: | \\) (\\ [a-zA-Z _ \ - \ s0-9 \.] +) +'. Valida la ruta correctamente en mi opinión. Encontrado aquí [aquí] (https://www.codeproject.com/Tips/216238/Regular-Expression-to-Validate-File-Path-and-Exten) – Potato

0

Regex Tester es un buen sitio web para probar la expresión regular rápido.

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