简体   繁体   中英

Non greedy regex is not working as expected

I need to take certain part from the string with regex non greedy approach. I am manipulating following string :

<a href="/guidance/">Hi</a> </li><li  > <a href="/news/institutional/2012/05/000001asdf">Thanks</a>

from which I need to get :

<a href="/news/institutional/2012/05/000001asdf">Thanks</a>

I've been trying with following regex :

<a.*?news/.*?/(\d{1,4}\/[01]?\d)?.*?</a>

but it gets all string instead of part of string mentioned above.As far as I understand .*? capture shortest match but it's not working as expected.

This [^>] is a negative character class, any character except angle
brace. This stops a non-greedy .*? from matching the end of the tag
(turning it semi-greedy) when it can't find the specific news anchor.

 #  @"(?s)<a[^>]*?news/[^>/]*?/(\d{1,4}(?:/\d+)*)?[^>]*?>.*?</a>"

 (?s)                  # Modifier, Dot-Matches any character
 <a                    # Open 'a' tag
 [^>]*?                # Any non '>' character
 news/                 # Need 'news/'
 [^>/]*?               # Any non '>' or '/' character
 /                     # Need '/'
 (                     # (1 start), Optional Date ?
      \d{1,4}               # 1-4 digit year
      (?: / \d+ )*          # month / day, etc ..
 )?                    # (1 end)
 [^>]*?                # Any non '>' character
 >                     # End Open '>' tag
 .*?                   # Anything
 </a>                  # Close 'a' tag 

C# example:

string news = @"
<a href=""/guidance/"">Hi</a> </li><li  > <a href=""/news/institutional/2012/05/000001asdf"">Thanks</a>
<a href=""/rintime/"">Hi</a> <a href=""/news/google/asdf"">GOOGLE</a>
";
Regex RxNews = new Regex(@"(?s)<a[^>]*?news/[^>/]*?/(\d{1,4}(?:/\d+)*)?[^>]*?>.*?</a>" );
Match _mNews = RxNews.Match( news );
while (_mNews.Success)
{
    Console.WriteLine("Found: {0}\r\nGroup 1 = {1}\r\n", _mNews.Groups[0].Value, _mNews.Groups[1].Value);
    _mNews = _mNews.NextMatch();
}

Output:

Found: <a href="/news/institutional/2012/05/000001asdf">Thanks</a>
Group 1 = 2012/05/000001

Found: <a href="/news/google/asdf">GOOGLE</a>
Group 1 =

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM