Exclude starts, but include ends with

I cannot figure it out myself, I need to match a string that starts with ASP. and ends with _aspx , but I need to exclude the start of the match (part of ASP. ).

For instance,

  string input = "random stack trace text ASP.filename_aspx random text"; Regex r = new Regex("Regular expression needed!!!"); var mc = r.Matches(s); foreach (var item in mc) { Console.WriteLine(item.ToString()); } 

And he needs to output something like this,

filename_aspx

+4
source share
3 answers

This is the job for a positive lookbehind statement :

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

(?<=\bASP\.) ensures that ASP. It is present immediately before the original match position, but it does not include it in the match result. \b is a word boundary binding that claims that we are not matching WASP , only ASP .

\S+ matches one or more characters without spaces (this assumes your file names do not contain spaces).

+6
source

This should do the trick for you, ASP\.(.+_.*?)\s , and here is Rubular to prove it .

Explanation

  • ASP\. - Searches for an ASP. string ASP. to determine the starting position.
  • (.+_.*?) - .+ finds any character 1 or more times, _ matches the underscore to make the assumption that we get to the end of the line, and .*? says he receives any character 0 or more times, but this is not a greedy match, so he will take as much as necessary until he reaches the next match.
  • \s - in the next match, it searches for a space, so you get the file name because .*? stops.
0
source

You can achieve this even without regular expression (which is more efficient):

 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

0
source

Source: https://habr.com/ru/post/1494516/


All Articles