问个正则的问题:
给一个字符串,如:“hello world!”
写个正则表达式,能且只能匹配字符串开头的字母,如:
"h"
"he"
"hell"
...
到
"hello world!"
只匹配这些字符串
怎么写?
一、/^h(e(l(l(o( (w(o(r(l(d(!?)?)?)?)?)?)?)?)?)?)?)?$/
// 生成字符串的前缀正则
function generatePrefixReg(str) {
let regLeft = '^', regRight = '$'
for (const word of str) {
regLeft += `${word}(`
regRight = `)?${regRight}`
}
return new RegExp(regLeft.slice(0, -1) + regRight.slice(1))
}
二、/^(h|he|hel|hell|hello|hello |hello w|hello wo|hello wor|hello worl|hello world|hello world!)$/