【发布时间】: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']
}
请帮忙!
【问题讨论】:
-
答案在this linked post。
-
编辑了问题
标签: c# regex expression