【问题标题】:Regex expression -string between first and last single quotes [duplicate]正则表达式 - 第一个和最后一个单引号之间的字符串[重复]
【发布时间】:2017-05-07 15:19:59
【问题描述】:

我有一些字符串。我想要第一个和最后一个单引号之间的总字符串 例如:

string val = "'Scale['#13212']'";   //--->Scale['#13212']
string val2= "'Scale[#13212']";     //--->Scale[#13212
string val3="abc'23'asad";          //--->23

我使用了以下regex-@".*'(.*?)'.*",但它只显示最后两个之间的字符串。

例如:

string val = "'Scale['#13212']'";   //--->]

当我使用 一对单引号 来捕获字符串和组(仅在组 [1] 中)的整个值时,它可以很好地处理贪心 但是当我想用 multiple pair of single quote 捕获一个字符串和一个组(仅在 group[1] 中)的整个值时,它只捕获用 括起来的字符串的值最后一对,但不是第一个和最后一个单引号之间的字符串。

例如:

string val1 = "Content:abc'23'asad";          //--->23
            string val2 = "Content:'Scale['#13212']'ta";

            Match match1 = Regex.Match(val1, @".*'(.*)'.*");
            Match match2 = Regex.Match(val2, @".*'(.*)'.*");
            if (match1.Success)
            {
                string value1 = match1.Value;
                string GroupValue1 = match1.Groups[1].Value;
                Console.WriteLine(value1);
                Console.WriteLine(GroupValue1);

                string value2 = match2.Value;
                string GroupValue2 = match2.Groups[1].Value;
                Console.WriteLine(value2);
                Console.WriteLine(GroupValue2);

                Console.ReadLine();

                // using greedy For val1 i am getting perfect value for-
                // value1--->Content:abc'23'asad
                // GroupValue1--->23

                // BUT using greedy For val2 i am getting the string elcosed by last single quote-
                // value2--->Content:'Scale['#13212']'ta
                // GroupValue2---> ]
                // But i want GroupValue2--->Scale['#13212']
            }

请帮忙!

【问题讨论】:

标签: c# regex expression


【解决方案1】:

只需在引号之间使用贪婪的.*

'(.*)'

Demo

【讨论】:

    【解决方案2】:

    您可以使用 Positive Lookbehind 和 Positive Lookahead 来获取引号之间的文本 (Demo)

    (?<=\').*(?=\')
    

    【讨论】:

    • 这是正确的答案
    【解决方案3】:

    试试下面

    string test= "'$get this$' test value";
    string getvalue = Regex.Match(test, @"\'(.*?)\'").Groups[1].ToString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 2014-08-12
      相关资源
      最近更新 更多