正则表达式面试题(山月)
如何使用正则匹配一个汉字
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 655(opens new window)
Author
回答者: wangjiayan(opens new window)
/\p{Unified_Ideograph}/u
Author
回答者: jkLennon(opens new window)
var pattern1 = /[\u4e00-\u9fa5]+/g; var contents = "[微笑][撇嘴][发呆][得意][流泪]"; var content = contents.match(pattern1);
实现一个 render/template 函数,可以用以渲染模板
更多描述
const template = '{{ user["name"] }},今天你又学习了吗 - 用户ID: {{ user.id }}';
const data = {
user: {
id: 10086,
name: "山月",
},
};
//=> "山月,今天你又学习了吗 - 用户ID: 10086"
render(template, data);
注意:
- 注意深层嵌套数据
- 注意
user['name']
属性
关于复杂的模板编译解析执行,可参考 mustache(opens new window) 与 handlebars.js(opens new window) :::
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 678(opens new window)
Author
回答者: shfshanyue(opens new window)
代码可见 实现一个 render/template 函数,可以用以渲染模板 - codepen(opens new window)
function get(source, path, defaultValue = undefined) {
// a[3].b -> a.3.b -> [a, 3, b]
const paths = path
.replace(/\[(\w+)\]/g, ".$1")
.replace(/\["(\w+)"\]/g, ".$1")
.replace(/\['(\w+)'\]/g, ".$1")
.split(".");
let result = source;
for (const p of paths) {
result = result?.[p];
}
return result === undefined ? defaultValue : result;
}
function render(template, data) {
return template.replace(/{{\s+([^\s]+)\s+}}/g, (capture, key) => {
return get(data, key);
});
}
Author
回答者: heretic-G(opens new window)
function render(template, data) {
return template.replace(/({{).*?(}})/g, function (...args) {
return Function(`return this.${args[0].slice(2, -2).trim()}`).call(data);
});
}
Author
回答者: haotie1990(opens new window)
function template(input, data) {
const regex = RegExp(/\{\{([\w|\.|\[|\]|"]+)\}\}/, "g");
let result;
while ((result = regex.exec(input)) !== null) {
// input字符串不能修改
const [pattern, key] = result;
// 由于改变了原字符串,但regex.lastIndex并未被重置,仍然从此位置开始匹配
input = input.replace(pattern, eval(`data.${key}`));
regex.lastIndex = 0; // 重置lastIndex;
}
return input;
}