spaasteam / spaas-daily-practice

spaas团队的每日一练,欢迎小伙伴们提交踊跃答案!
4 stars 2 forks source link

第 51 题: 字符串模式匹配 #64

Open JE-lee opened 5 years ago

JE-lee commented 5 years ago

要求实现一个工具函数,根据传入的字符串模式,(模式只用x表达,比如说xxx-xxx-xx), 返回一个判断字符串模式的函数

function generate(pattern){
  return function(){}
}

// test
// 下面的x表示数字
let pattern1 = generate('xxx-xxxx-xxxx')
console.log(pattern1('136-1234-1234')) // true
console.log(pattern1('136-123-1234')) // false

let pattern2 = generate('x-xx-xxx')
console.log(pattern2('1-12-123')) // true
console.log(pattern2('2-13-234')) // true
console.log(pattern2('2-13222-234')) // false

let pattern3 = generate('xxx:xx:xx')
console.log(pattern3('136:123:12')) // true
console.log(pattern3('1234:12')) // false
Htongbing commented 5 years ago
function generate(pattern) {
  const reg = new RegExp(`^${pattern.replace(/([()\^$*+?{}.|\[\]\\])/g, '\\$1').replace(/x/g, '\\w')}$`)
  return function verify(str) {
    return reg.test(str)
  }
}

// test
// 下面的x表示数字
let pattern1 = generate('xxx-xxxx-xxxx')
console.log(pattern1('136-1234-1234')) // true
console.log(pattern1('136-123-1234')) // false

let pattern2 = generate('x-xx-xxx')
console.log(pattern2('1-12-123')) // true
console.log(pattern2('2-13-234')) // true
console.log(pattern2('2-13222-234')) // false

let pattern3 = generate('xxx:xxx:xx')
console.log(pattern3('136:123:12')) // true
console.log(pattern3('1234:12')) // false

let pattern4 = generate('[xx(xx\d]xx)^z$xx*xx+xx?xx{xx}xx.xx|xx')
console.log(pattern4('[11(22\d]33)^z$44*55+66?77{88}99.10|11')) // true
cjfff commented 5 years ago
const generatePattern = (patternStr) => (str) => new RegExp(patternStr.replace(/x/g, ".")).test(str);

let pattern1 = generatePattern('xxx-xxxx-xxxx')
console.log(pattern1('136-1234-1234')) // true
console.log(pattern1('136-123-1234')) // false

let pattern2 = generatePattern('x-xx-xxx')
console.log(pattern2('1-12-123')) // true
console.log(pattern2('2-13-234')) // true
console.log(pattern2('2-13222-234')) // false

let pattern3 = generatePattern('xxx:xxx:xx')
console.log(pattern3('136:123:12')) // true
console.log(pattern3('1234:12')) // false