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 /<.+&开发者_开发百科gt;/
have been more adequate?
In this case, it make *
lazy.
1*
- match as many 1
s as possible.
1*?
- match as few 1
s 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.
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.
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.
that's the best website I found about regex after the regex library:
http://www.wellho.net/regex/java.html
Hope that helps!
精彩评论