关于正则表达式的问题

时间:2011-03-08 06:54:45

标签: c# regex

我有代码

s = Regex.Match(item.Value, @"\/>.*?\*>", RegexOptions.IgnoreCase).Value;

它返回类似'/> test *>'的字符串,我可以替换符号'/>'和'*>',但是如何在没有这个符号的情况下返回字符串,只在它们之间输入字符串'test'?

3 个答案:

答案 0 :(得分:2)

您可以在regx中对模式进行分组,并从匹配中获取

var    match= Regex.Match(item.Value, @"\/>(?<groupName>.*)?\*>", RegexOptions.IgnoreCase);
 var data= match.Groups["groupName"].Value

答案 1 :(得分:2)

您可以通过在区域周围放置()来保存正则表达式的部分内容。所以对你的例子来说:

// item.Value ==  "/>test*>"
Match m = Regex.Match(item.Value, @"\/>(.*?)\*>");
Console.WriteLine(m.Groups[0].Value); // prints the entire match, "/>test*>"
Console.WriteLine(m.Groups[1].Value); // prints the first saved group, "test*"

我也删除了RegexOptions.IgnoreCase,因为我们没有专门处理任何字母,大概是/>看起来像什么? :)

答案 2 :(得分:1)

您也可以使用look-ahead and look-behind。对于你的例子,它将是:

var value = Regex.Match(@"(?<=\/>).*?(?=\*>)").Value;
相关问题