Re: [問題] 請問括號的神奇作用

看板RegExp作者 (小a)時間15年前 (2009/02/28 23:17), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串5/6 (看更多)
※ 引述《grence (多想兩分鐘 = =")》之銘言: : 弄成簡單的例子.... : <script type='text/javascript'> : var htmlText="<body> ... <body> .... </body> .. </body>"; : alert(/<body>/g.exec(htmlText));//<body> : alert(/(<body>)/g.exec(htmlText));//<body>,<body> : </script> : IE7 跟 FireFox的結果一樣,我也很好奇這兩個差在哪裡… 原以為 因為有兩個body 所以有加()的傳回兩個body 但看來不是... 而且傳回的都是第一個body <script type='text/javascript'> var htmlText="<bodya> ... <bodyb> .... </body> .. </body>"; alert(/(<body.?>)/g.exec(htmlText)); //<bodya>,<bodya> alert(/<body.?>/g.exec(htmlText)); //<bodya> </script> 就算只給一個body 有加()的還是會傳回 <body>,<body> -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.232.172.163

02/28 23:21, , 1F
Opera
02/28 23:21, 1F

03/01 00:40, , 2F
感覺很像是BUG…該不會 IE 和 FF 的 BUG 都一樣吧?
03/01 00:40, 2F
補充一下... <script type='text/javascript'> var htmlText="<bodya> .. <bodyb> .... <bodyc>"; alert( "A: " + htmlText.match(/(<body.?>)/g) ); // A: <bodya>,<bodyb>,<bodyc> alert( "B: " + htmlText.match(/(<body.?>)/g).length ); // B: 3 alert( "C: " + htmlText.match(/(<body.?>)/g)[0] ); // C: <bodya> alert( "D: " + htmlText.match(/(<body.?>)/g)[1] ); // D: <bodyb> alert( "E: " + htmlText.match(/(<body.?>)/g)[2] ); // E: <bodyc> alert( "F: " + htmlText.match(/(<body.?>)/g)[3] ); // F: undefined </script> 以下取自 http://www.w3schools.com/jsref/jsref_obj_regexp.asp exec() Search a string for a specified value. Returns the found value and remembers the position match() Search a string for a specified value. Returns an array of the found value(s) ( ) Finds the group of characters inside the parentheses and stores the matched string

03/01 01:09, , 3F
爆... XD
03/01 01:09, 3F
※ 編輯: giacch 來自: 118.232.172.163 (03/01 01:17)
文章代碼(AID): #19gLMd8V (RegExp)
討論串 (同標題文章)
文章代碼(AID): #19gLMd8V (RegExp)