[·Òë]High Performance JavaScript(016)
Regular Expression Optimization ÕýÔò±í´ïʽÓÅ»¯
Incautiously crafted regexes can be a major performance bottleneck (the upcoming section, "Runaway Backtracking" on page 91, contains several examples showing how severe this can be), but there is a lot you can do to improve regex efficiency. Just because two regexes match the same text doesn't mean they do so at the same speed.
´ÖdzµØ±àдÕýÔò±í´ïʽÊÇÔì³ÉÐÔÄÜÆ¿¾±µÄÖ÷ÒªÔÒò£¨ºóÃæ“»ØËÝʧ¿Ø”Ò»½ÚÓÐһЩÀý×Ó˵Ã÷ÕâÊǶàôÑÏÖصÄÎÊÌ⣩£¬µ«»¹Óкܶà¿ÉÒԸĽøÕýÔò±í´ïʽЧÂʵĵط½¡£Á½¸öÕýÔò±í´ïʽƥÅäÏàͬµÄÎı¾²¢²»Òâζ×ÅËûÃǾßÓÐͬµÈµÄËٶȡ£
Many factors affect a regex's efficiency. For starters, the text a regex is applied to makes a big difference because regexes spend more time on partial matches than obvious nonmatches. Each browser's regex engine also has different internal optimizations.
Ðí¶àÒòËØÓ°ÏìÕýÔò±í´ïʽµÄЧÂÊ¡£Ê×ÏÈ£¬ÕýÔò±í´ïʽÊÊÅäµÄÎı¾Ç§²îÍò±ð£¬²¿·ÖÆ¥Åäʱ±ÈÍêÈ«²»Æ¥ÅäËùÓõÄʱ¼äÒª³¤¡£Ã¿ÖÖä¯ÀÀÆ÷µÄÕýÔò±í´ïʽÒýÇæÒ²Óв»Í¬µÄÄÚ²¿ÓÅ»¯¡£
Regex optimization is a fairly broad and nuanced topic. There's only so much that can be covered in this section, but what's included should put you well on your way to understanding the kinds of issues that affect regex performance and mastering the art of crafting efficient regexes.
ÕýÔò±í´ïʽµÄÓÅ»¯ÊÇÒ»¸öÏ൱¹ã·ººÍϸÖÂÈë΢µÄ»°Ìâ¡£±¾½ÚÌÖÂÛ¾¡ÆäËùÄÜ£¬Ï£ÍûÕâЩÄÚÈÝÓÐÖúÓÚÄúÀí½âÓ°ÏìÕýÔò±í´ïʽÐÔÄܵĸ÷ÖÖÎÊÌâºÍÕÆÎÕ±àд¸ßЧÕýÔò±í´ïʽµÄÒÕÊõ¡£
Note that this section assumes you already have some experience with regular expressions and are primarily interested in how to make them faster. If you're new to regular expressions or need to brush up on the basics, numerous resources are available on the Web and in print. Regular Expressions Cookbook (O'Reilly) by Jan Goyvaerts and Steven Levithan (that's me!) is written for people who like to learn by doing, and
Ïà¹ØÎĵµ£º
Ò³ÃæÌá½»Êý¾ÝÒ»°ãÓÐÁ½ÖÖ·½·¨£ºget,post¡£post¾ÍÊÇËùνµÄformÌá½»£¬Ê¹ÓÃÊÓͼ£»getÊÇͨ¹ýurlÌá½»¡£
Get·½·¨Ò»°ãÓúǫ́´úÂ루Èçasp,asp.net£©»ñµÃ²ÎÊý£¬´úÂëºÜ¼òµ¥£ºRequest.QueryString["id"];¼´¿É»ñÈ¡¡£
ÓÐЩʱºòÐèÒªÖ±½ÓÔÚǰ̨»ñÈ¡url²ÎÊý£¬ÒªÓõ½javascript£¬jsûÓÐÖ±½Ó»ñÈ¡url²ÎÊýµÄ·½·¨£¬ÄÇô£¬ÎÒÃÇÈçºÎͨ¹ýjs ......
ÃæÏò¶ÔÏóµÄÓïÑÔ¶àÊý¶¼Ö§³Ö¼Ì³Ð£¬¼Ì³Ð×îÖØÒªµÄÓŵã¾ÍÊÇ´úÂ븴Ó㬴Ӷø¹¹½¨´óÐÍÈí¼þϵͳ¡£Èç¹ûÒ»¸öÀàÄܹ»ÖØÓÃÁíÒ»¸öÀàµÄÊôÐԺͻò·½·¨£¬¾Í³Æ֮Ϊ¼Ì³Ð¡£
´ÓÕâ¸ö½Ç¶ÈÀ´¿´¿´jsµÄ¼Ì³Ð·½Ê½¡£jsÖм̳з½Ê½ÓëдÀ෽ʽϢϢÏà¹Ø¡£²»Í¬µÄдÀ෽ʽÔì³É²»Í¬µÄ¼Ì³Ð·½Ê½¡£¸÷ÖÖÁ÷ÐÐjs¿â¼Ì³Ð·½Ê½Ò²¸÷²»Ïàͬ¡£´Ó×î¼òµ¥µÄ
¸´ÓÿªÊ¼¡£
1¡¢¹¹Ôìº ......
µÚÎåÕ Strings and Regular Expressions ×Ö·û´®ºÍÕýÔò±í´ïʽ
Practically all JavaScript programs are intimately tied to strings. For example, many applications use Ajax to fetch strings from a server, convert those strings into more easily usable JavaScript objects, and ......