最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Purpose of (.+?) in regular expressions - Stack Overflow

programmeradmin1浏览0评论

I am kinda new to this Regex thing.

When analyzing some code I frequently e across the pattern .+? or (.+?)

I can't seem to find the meaning of this pattern using my noobish deductive reasoning.

I am kinda new to this Regex thing.

When analyzing some code I frequently e across the pattern .+? or (.+?)

I can't seem to find the meaning of this pattern using my noobish deductive reasoning.

Share Improve this question edited Jul 9, 2011 at 6:41 Brad Mace 27.9k18 gold badges109 silver badges152 bronze badges asked Mar 15, 2010 at 23:08 Dennis DDennis D 1,3434 gold badges17 silver badges24 bronze badges 1
  • regular-expressions.info/repeat.html explains it quite well – user187291 Commented Mar 15, 2010 at 23:16
Add a ment  | 

2 Answers 2

Reset to default 13

. means any character (except a new line). + means one or more. ? in this context mean lazy or non-greedy. That means it will try to match the absolute minimum of characters that satisfy the quantifier. Example:

> 'abc'.match(/.+/)
["abc"]
> 'abc'.match(/.+?/)
["a"]
> 'abc'.match(/.*/)
["abc"]
> 'abc'.match(/.*?/)
[""]

It depends what kind of knowledge you have about patterns. Here's an explanation that assumes you have some kind of basic idea about what regular expressions are:

  • . matches any character
  • + means repeat the last pattern 1 or more times
  • so far, .+ means one or more characters
  • ? means ungreedy, which means the matching will stop with the first occasion.

A quick explanation on greediness:

/.+X/.exec("aaaXaaaXaaa");
["aaaXaaaX"]
/.+?X/.exec("aaaXaaaXaaa");
["aaaX"]

As you can see, the ? character makes the search ungreedy, thus matching as little as possible.

发布评论

评论列表(0)

  1. 暂无评论