四种情况:
s*
.*
.
export default (str, pattern) => {
/**
* 如何分组?
* split?
* 1.如何用于分组的断点不被刨除。
* 2.断点进行分组
* match?
* 1.将字符串完全匹配
* 2.需要分组的部分使用排他性的组合
*/
const modeArr = pattern.match(/([a-z.]\*)|(\.)|([a-z]+(?=([a-z.]\*)|$))/g)
// const modeArr = pattern.split(/([a-z.]\*)|(\.)|([a-z]+(?=([a-z.]\*)|$))/g).filter(item => !!item)
let rest = str
for (let i = 0, length = modeArr.length; i < length; i++) {
const mode = modeArr[i]
if (mode.indexOf('.') !== -1 || mode.indexOf('*') !== -1) {
if (mode === '.') {
rest = rest.slice(1)
} else if (mode === '.*') {
rest = rest.slice(rest.match(new RegExp(`${rest.charAt(0)}*`))[0].length)
} else {
if (rest.charAt(0) === mode[0]) {
rest = rest.slice(rest.match(new RegExp(`${rest.charAt(0)}*`))[0].length)
} else {
return false
}
}
} else {
if (rest.slice(0, mode.length) === mode) {
rest = rest.slice(mode.length)
} else {
return false
}
}
}
if (rest) {
return false
}
return true
}
测试用例
import regModeStr from '../../code/regexp/lesson2'
test('regModeStr', () => {
expect(regModeStr('aaa', 'caa*')).toBe(false)
})
test('regModeStr:2', () => {
expect(regModeStr('aaabc', 'a*bc')).toBe(true)
})
test('regModeStr:3', () => {
expect(regModeStr('aaabc', 'a*.*')).toBe(false)
})
test('regModeStr:4', () => {
expect(regModeStr('aa', '.a')).toBe(true)
})
test('regModeStr:5', () => {
expect(regModeStr('aab', '.*')).toBe(false)
})