24
2021
04

Get Coating Colour Data from Component Description using RegExp match()

var component = `white paper sheet with transparent plastic film and (lacquer, gold color foil, silver color foil) coatings and inaccessible multicolor printings`
  
var reg = /(?:.*(?:and|with))(.*)(coatings?|lacquer)/       // match() 會匹配RegExp中的信息; 如果有多個括號,則會以數組顯示所有括號匹配的信息。                                   //
                                                            // match()[0]代表完全匹配,會顯示匹配的前後項目 (and|with)(.*)(coatings?|lacquer),
                                                            // match()[1]會匹配第一個括號的值,即(.*),下面會解釋為什麼是(.*)而不是(?:.*(?:and|with))
                                                            // match()[2]會匹配第二個括號的值,即(coatings?|lacquer)
                                                            // 所以如果RegExp中沒有括號, match()[1]因為不能匹配第一個括號的值,會傳回null.
                                                            // ?:使得括號中匹配的信息不會被記憶,所以第一個記憶的括號就是(.*),第二就是(coatings?|lacquer)
                                                            // .*(and|with)即由第一個文字開始,匹配至and或with結束,因為RegExp不是.*?(and|with, 
                                                            // 所以會匹配由即由第一個文字開始,到最後一個and或with之間的文字,將這個匹配到的文字作為開始,
                                                            // coatings?|lacquer 作為結束, ?代表前一個字s匹配0至1次,|代表或, 所以coatings?|lacquer代表匹配coating,coatings或lacquer。
                                                            // 首先會.*(and|with)會匹配到`white paper... coatings and`的文字,
                                                            // 但component 句子中找不到中 以這個文字作開始,以coatings?|lacquer為結束,中間文字的信息,
                                                            // 所以.*(and|with)會匹配由第一個文字開始,至倒數第二個and或with結束文字的信息,即`white paper ... plastic film and`
                                                            // 之後以這個文字作為開始,以coatings?|lacquer為結束,中間文字的信息,因為(.*)中沒有?號,即(.*?),所以會匹配至最後一個coatings?|lacquer
                                                            // 就能成功匹配到(.*)內容,即(lacquer, gold color foil, silver color foil)
                                                            // match()匹配完成,match()[1]顯示匹配第一個括號的值,即(lacquer, gold color foil, silver color foil)

                                                            

                                                           // replace(/[\(\)]/g,"") 即代表刪除match()匹配中的所有括號; trim() 代表除前後空格

                                                            // coating文字split完,號會變數組,之後用map映射出數組中文字trim()後的值。
  
var coating = component.match(reg)[1].replace(/[\(\)]/g,"").trim().split(",").map(str => str.toString().trim())
console.log(coating)                                        //就能得出 coating colour data


« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。