【问题标题】:C# Regular Expressions, string between single quotesC#正则表达式,单引号之间的字符串
【发布时间】:2011-04-14 11:56:57
【问题描述】:
string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";

我想使用正则表达式获取' 引号之间的文本。

任何人都可以吗?

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    应该这样做:

    string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
    
    Match match = Regex.Match(val, @"'([^']*)");
    if (match.Success)
    {
        string yourValue = match.Groups[1].Value;
        Console.WriteLine(yourValue);
    }
    

    表达式'([^']*)的解释:

     '    -> find a single quotation mark
     (    -> start a matching group
     [^'] -> match any character that is not a single quotation mark
     *    -> ...zero or more times
     )    -> end the matching group
    

    【讨论】:

    • 这是非常有用的解释。但是为什么要分组[1]?
    • @liang 第一组 (match.Groups[0]) 将包含与整个正则表达式匹配的完整字符串。这意味着它还包含前导引号字符。 match.Groups[1] 包含正则表达式中的第一个匹配组,这就是我们要使用的值。
    • 不知道组,但这正是有很大帮助的! +1
    【解决方案2】:

    您正在寻找使用正则表达式匹配字符串中的 GUID。

    这就是你想要的,我怀疑!

    public static Regex regex = new Regex(
      "(\\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-"+
      "([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\\}{0,1})",RegexOptions.CultureInvariant|RegexOptions.Compiled);
    
    Match m = regex.Match(lineData);
    if (m.Succes)
    {
    ...
    }
    

    【讨论】:

      【解决方案3】:

      这将提取一行中 firstlast 单引号之间的文本:

      string input = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
      Regex regName = new Regex("'(.*)'");
      Match match = regName.Match(input);
      if (match.Success)
      {
          string result = match.Groups[1].Value;
          //do something with the result
      }
      

      【讨论】:

      • 如果你有 'a', 'b' 这将得到一个字符串 "a', 'b" 而不是预期的 "a"。 @Fredrik's 会这样做。
      【解决方案4】:

      您也可以使用积极的前瞻和后瞻,

      string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
      
      Match match = Regex.Match(val, @"(?<=')[^']*(?=')");
      if (match.Success)
      {
          string yourValue = match.Groups[0].Value;
          Console.WriteLine(yourValue);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-13
        • 2013-07-18
        • 1970-01-01
        • 2012-09-26
        相关资源
        最近更新 更多