【NodeJS】替换模糊查询字符里包含的正则关键字
-
问题:正则匹配时字符串中包含了一些特殊字符,导致查询失败
例如,下面的字符包含了( 和 ),这在正则中属于特殊字符(-)-magnocurarine
正则中的特殊字符如下图
-
思路:
1、映射查询字符串的索引位置和对应位置的字符Object {0: "(", 1: "-", 2: ")", 3: "-", 4: "m", 5: "a", 6: "g", 7: "n", 8: "o", 9: "c", 10: "u", 11: "r", 12: "a", …}
2、标记出特殊字符所在的索引位置和字符信息
Object {0: "\\(", 2: "\\)"}
3、在查询字符中匹配出特殊字符
async regex_include_keyword(param) { const key_word = ['$','(',')','*', '+','.','[','?','\\','^','{','}','|' ] let str_index = 0; let str_map_dict = {} let conflict_map_dict = {} for (let p of param) { Object.assign(str_map_dict, { [str_index]: p }) for (let key of key_word) { if (p == key) { Object.assign(conflict_map_dict, { [str_index]: "\\" + key }) } } ++str_index; } for (let key of Object.keys(conflict_map_dict)) { str_map_dict[key] = conflict_map_dict[key] } let search_str = "" for (let v of Object.values(str_map_dict)) { search_str += v } return search_str }
- 返回的结果
"\\(-\\)-magnocurarine"