Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Non-Greedy (Lazy)

I'm attempting to non-greedily parse out TD tags. I'm starting with something like this:

<TD>stuff<TD align="right">More stuff<TD align="right>Other stuff<TD>things<TD>more things 

I'm using the below as my regex:

Regex.Split(tempS, @"\<TD[.\s]*?\>"); 

The records return as below:

"" "stuff<TD align="right">More stuff<TD align="right>Other stuff" "things" "more things" 

Why is it not splitting that first full result (the one starting with "stuff")? How can I adjust the regex to split on all instances of the TD tag with or without parameters?

like image 888
steventnorris Avatar asked Dec 12 '12 16:12

steventnorris


People also ask

How do I make regex not greedy?

To make the quantifier non-greedy you simply follow it with a '?' the first 3 characters and then the following 'ab' is matched. greedy by appending a '?' symbol to them: *?, +?, ??, {n,m}?, and {n,}?.

What is greedy and non-greedy in regex?

It means the greedy quantifiers will match their preceding elements as much as possible to return to the biggest match possible. On the other hand, the non-greedy quantifiers will match as little as possible to return the smallest match possible. non-greedy quantifiers are the opposite of greedy ones.

How do you make part of a Perl regular expression Non-greedy?

To use non-greedy Perl-style regular expressions, the ? (question mark) may be added to the syntax, usually where the wildcard expression is used. In our above example, our wildcard character is the . * (period and asterisk). The period will match any character except a null (hex 00) or new line.

What is greedy vs non-greedy matching?

So the difference between the greedy and the non-greedy match is the following: The greedy match will try to match as many repetitions of the quantified pattern as possible. The non-greedy match will try to match as few repetitions of the quantified pattern as possible.


1 Answers

For non greedy match, try this <TD.*?>

like image 65
Jason Avatar answered Sep 20 '22 13:09

Jason