【发布时间】:2011-04-14 11:56:57
【问题描述】:
string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
我想使用正则表达式获取' 引号之间的文本。
任何人都可以吗?
【问题讨论】:
string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
我想使用正则表达式获取' 引号之间的文本。
任何人都可以吗?
【问题讨论】:
应该这样做:
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
【讨论】:
match.Groups[0]) 将包含与整个正则表达式匹配的完整字符串。这意味着它还包含前导引号字符。 match.Groups[1] 包含正则表达式中的第一个匹配组,这就是我们要使用的值。
您正在寻找使用正则表达式匹配字符串中的 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)
{
...
}
【讨论】:
这将提取一行中 first 和 last 单引号之间的文本:
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
}
【讨论】:
您也可以使用积极的前瞻和后瞻,
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);
}
【讨论】: