排除开头但包含结尾

时间:2013-07-31 14:01:07

标签: c# regex string match

我无法弄清楚自己,我必须匹配以ASP.开头并以_aspx结尾的字符串,但我需要排除匹配的开头({{1部分)。

例如,

ASP.

它需要输出这样的东西,

  

filename_aspx

3 个答案:

答案 0 :(得分:6)

这是positive lookbehind assertion

的工作
Regex r = new Regex(@"(?<=\bASP\.)\S+_aspx");

(?<=\bASP\.)确保ASP.出现在匹配的起始位置之前,但不会在匹配结果中包含它。 \bword boundary anchor,声称我们与WASP不匹配,仅与ASP匹配。

\S+匹配一个或多个非空白字符(假设您的文件名不包含空格)。

答案 1 :(得分:0)

这应该可以帮到你,ASP\.(.+_.*?)\s,这里有一个Rubular to prove it

<强>解释

  • ASP\. - 搜索字符串ASP.以确定起始位置。
  • (.+_.*?) - .+找到任意字符1次或多次,_匹配下划线以假设我们到达字符串的末尾,.*?说得到任何一个角色0次或更多次但是这是一个非贪婪的比赛所以它只需要尽可能多的必要,直到它到达下一场比赛。
  • \s - 下一场比赛,它会查找空格,因此您会获得文件名,因为.*?会停止。

答案 2 :(得分:0)

即使没有正则表达式(效率更高),您也可以实现这一目标:

string text = "blub ASP.filename_aspx foo ASP.filename2_aspx bah ...";
var matches = new List<string>();
int index = text.IndexOf("ASP", StringComparison.OrdinalIgnoreCase);
int endIndex = index >= 0 ? text.IndexOf("_aspx", index + 1, StringComparison.OrdinalIgnoreCase) : -1;
while (index >= 0 && endIndex >= 0)
{
    index += "ASP.".Length;
    endIndex += "_aspx".Length;
    matches.Add(text.Substring(index, endIndex - index));
    index = text.IndexOf("ASP", endIndex + 1, StringComparison.OrdinalIgnoreCase);
    endIndex = index >= 0 ? text.IndexOf("_aspx", index + 1, StringComparison.OrdinalIgnoreCase) : -1;
}

Demo

相关问题