tags:

views:

111

answers:

5

I'm following along a tutorial (Ruby) that uses a regex to remove all html tags from a string:

product.description.gsub(/<.*?>/,'').

I don't know how to interpret the ?. Does it mean: "at least one of the previous"? In that case, wouldn't /<.+>/ have been more adequate?

+8  A: 

In this case, it make * lazy.

1* - match as many 1s as possible.
1*? - match as few 1s as possible.

Here, when you have <a>text<b>some more text, <.*> will match <a>text<b>.
<.*?>, however, will match <a> and <b>.

See also: Laziness Instead of Greediness

Another important note here is that this regex can easily fail on valid HTML, it is better to use an HTML parser, and get the text of your document.

Kobi
A: 

Quantifiers such as * are greedy by default. This means they match as much as possible. Adding ? after them makes them lazy so they stop matching as soon as possible.

Daniel Egeberg
+6  A: 

By default .* is greedy which means that it matches as much as possible. So with .* the replacement would change:

This <b>is</b> an <i>example</i>.
     ^-------------------------^

to

This .

If you use a question mark after a quantifier it makes it non-greedy, so that it matches as little as possible. With .*? the replacement works as follows:

This <b>is</b> an <i>example</i>.
     ^-^  ^--^    ^-^       ^--^

Becomes:

This is an example.

This is different from the more common use of ? as a quantifier where it means 'match zero or one'.

Either way if your text is HTML you should use a HTML parser instead of regular expressions.

Mark Byers
+1 I like your examples.
alex
A: 

look at this video..

http://www.phpvideotutorials.com/regex/

you will understand the basics

Harsha M V
A: 

that's the best website I found about regex after the regex library:

http://www.wellho.net/regex/java.html

Hope that helps!

Saher