【问题标题】:Regex to match a path in C#正则表达式匹配 C# 中的路径
【发布时间】:2011-10-18 09:07:47
【问题描述】:

我是正则表达式的新手。我需要从以下几行中提取路径:

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

我需要实现一个返回给定行的路径的方法。第一列是一个包含 1 个或多个字符的单词,从不为空,第二列是路径。分隔符可以是 1 个或多个空格,也可以是一个或多个制表符,或两者兼而有之。

【问题讨论】:

  • 输入是文件还是单独的行?
  • 是的。对行和对文件的处理是不同的。除非你从 tex 文件中逐行读取它,然后你还需要处理换行符等。

标签: c# regex string parsing .net-1.1


【解决方案1】:

听起来你只是想要

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

(这是假设第一列从不包含空格或制表符。)

编辑:作为正则表达式,您可能只是这样做:

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

示例代码:

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;
    }    
}

【讨论】:

  • 路径可以有空格,所以第二个很糟糕。
  • @Jon:抱歉,我需要一个常规表达式,因为我使用的是 .NET 1.1,并且我无法访问 StringSplitOptions.RemoveEmptyEntries 重载。还是谢谢!
  • @DanielPeñalba:一开始就这么说会很有用——如今需要 .NET 1.1 的情况非常少见。将编辑。
【解决方案2】:
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
}

细分:

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

【讨论】:

  • 这看起来很复杂,基本上在第一组空格/制表符之后得到所有东西。
  • @JonSkeet 我同意。这是 Windows 路径的更通用的正则表达式。
  • @FailedDev 它不适用于例如“k:\test\test”。如果我尝试通过 \\test\t> 之类的路径,它将是有效的。我找到了这个正则表达式^(?:[c-zC-Z]\:|\\)(\\[a-zA-Z_\-\s0-9\.]+)+。我认为它正确地验证了路径。找到了here
【解决方案3】:

Regex Tester 是一个快速测试正则表达式的好网站。

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

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    • 2022-08-11
    • 2021-08-31
    • 2011-11-19
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多