加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 贪婪与非贪婪

发布时间:2020-12-14 01:31:47 所属栏目:百科 来源:网络整理
导读:The three kinds of regular expression quantifiers are greedy,reluctant,and possessive. A greedy quantifier starts by looking at the entire string for a match. If no match is found,it eliminates the last character in the string and tries ag

The three kinds of regular expression quantifiers are greedy,reluctant,and possessive.


A greedy quantifier starts by looking at the entire string for a match. If no match is found,it eliminates
the last character in the string and tries again. If a match is still not found,the last character is again
discarded and the process repeats until a match is found or the string is left with no characters. All the
quantifiers discussed to this point have been greedy.


A reluctant quantifier starts by looking at the first character in the string for a match. If that character
alone isn’t enough,it reads in the next character,forming a string of two characters. If still no match isfound,a reluctant quantifier continues to add characters from the string until either a match is found or
the entire string is checked without a match. Reluctant quantifiers work in reverse of greedy quantifiers.
A Possessive quantifier only tries to match against the entire string. If the entire string doesn’t produce a match,no further attempt is made. Possessive quantifiers are,in a manner of speaking,a one-shot deal.

What makes a quantifier greedy,or possessive? It’s really all in the use of the asterisk,question
mark,and plus symbols. For example,the question mark alone (?) is greedy,but a question mark fol-
lowed by another question mark (??) is reluctant. To make the question mark possessive,append a plus
sign (?+). The following table shows all the greedy,and possessive versions of the quantifiers
you’ve already learned.


wKiom1RjXT-w5gl0AAEaYfr6ups392.jpg


Notes:Browser support for possessive quantifiers leaves much to be desired. InternetExplorer and Opera don’t support possessive quantifiers and throw an error whenyou try to use one. Mozilla won’t throw an error,but it treats possessive quantifiersas greedy.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读