学无先后,达者为师

网站首页 编程语言 正文

获取字符串大括号里面的值 ,并判断字符串是否符合要求

作者:让时光到此为止。 更新时间: 2022-02-15 编程语言

一个特殊的需求:要求找出双大括号中间的值

let str = '我的名字叫{{让时光到此为止}},今年{{5}}岁了,是一个{{学生}}'
let rep =  str.match(/(?<=\{\{)[^}]*(?=\}\})/g)
let rep2 =  str.match(/\{\{(.*?)\}\}/g)
// 输出的是{{}} 两个大括号中间的内容并返回一个数组
console.log(rep ) // ["让时光到此为止", "5", "学生"]
// 输出的是{{}} 和 两个大括号中间的内容并返回一个数组
console.log(rep2 ) // ["{{让时光到此为止}}", "{{5}}", "{{学生}}"]

如果给出的字符串中两个括号不对称怎么办呢? 比如:

‘我的{{{名字叫{{{{{{让时光到此为止}},今年{{5}}岁了,是一个{{学生}}’

这种情况就需要我们去判断字符串是否符合我们的要求了,如果不符合要求,需要提示错误

/**
 * 判断当前字段串左右双大括号有无结束
 * @param str 字符串
 */
 let str = '我的名字叫{{让时光到此为止}},今年{{5}}岁了,是一个{{学生}}'
 let str2 =  '我的{{{名字叫{{{{{{让时光到此为止}},今年{{5}}岁了,是一个{{学生}}'
 console.log(bracketCheck(str)) // false
 console.log(bracketCheck(str2)) // true
export const bracketCheck = (str)=>{
  let arr = str.split('') // 将字符串转化为数组
  // StackBase 是一个简易栈,大家也可以用数组代替
  let stack = new StackBase() // 新建栈
  let aString ='{}' // 用来匹配的字符串
  for(let i of arr){
    if( aString.indexOf(i)!==-1){ // 左右括号
      stack.push(i)
      if(stack.length()===4){
        let target = stack.pop(),
            target2 = stack.pop(),
            target3 = stack.pop(),
            target4 = stack.pop()
        if(target !== target2 || target3 !== target4 ||
            target !=='}' || target4!=='{'
          ){
            return false
        }
      }
    }
  }
  return stack.length()===0? true: false
}
/**
 * 简易栈
 */
export class StackBase{
    constructor(public dataStore?: any[],public top?: number) {
        this.dataStore = []
        this.top = 0 // 初始化为0
    }
    push(element){ // 入栈
        this.dataStore[this.top++] = element
    }
    pop(){ // 出栈
        return this.dataStore[--this.top]
    }
    peek(){ // 查看栈顶元素
        return this.dataStore[this.top-1]
    }
    clear(){ // 清空栈
        this.top=0
    }
    length(){ // 栈内存放的元素个数
        return this.top
    }
}

原文链接:https://blog.csdn.net/qq_35257117/article/details/105486604

栏目分类
最近更新