匹配如下规则的正则表达式怎么写

学号57
  • 0
新手上路,请多包涵

匹配如下规则的正则表达式怎么写(要求是只能输入数字,英文字母,运算符号,小括号)

(38+2L+3O+4Q4-2C-2*H-2-Q3)/10

回复
阅读 311
1 个回答

如果只是要验证字符串所包含的字符集是否正确可以写成这样

/^[a-z0-9A-Z+*/)(-]+$/

如果要验证改表达式语法是否正确则可使使用以下代码(不支持正负数比如-1或者1-+1都会被判断为false)

const validateExpression = (expression: string): boolean => {
  let index = 0
  const RENumberLiteral = /[a-z0-9A-Z]/

  const skipBlank = (): void => {
    while (index < expression.length && expression[index] === ' ') ++index
  }

  const validateOperator = (): boolean => {
    switch (expression[index]) {
      case '+':
      case '-':
      case '*':
      case '/':
        ++index
        return true
      default:
        return false
    }
  }

  const validateNumber = (): boolean => {
    let matched = ''

    while (
      index < expression.length &&
      RENumberLiteral.test(expression[index])
    ) {
      matched += expression[index]
      ++index
    }

    return !!matched.length
  }

  const consume = (char: string): void => {
    if (expression[index] === char) ++index
    else throw new Error(`Expected ${char} but got ${expression[index]} `)
  }

  const validate = (): boolean => {
    let res = false

    if (expression[index] === '(') {
      skipBlank()
      consume('(')
      skipBlank()
      res = validate()
      if (!res) return res
      skipBlank()
      consume(')')
      skipBlank()
      if (index < expression.length) {
        if (expression[index] === ')') return res
        res = validateOperator()
        if (res) {
          res = validate()
        }
      }
    } else {
      skipBlank()
      res = validateNumber()
      skipBlank()
      if (res && index < expression.length) {
        if (expression[index] === ')') return res
        res = validateOperator()
        skipBlank()
        if (res) {
          res = validate()
        }
      }
    }

    return res
  }

  return validate()
}

console.log(validateExpression('1+2')) //true
console.log(validateExpression('1+')) //false
console.log(validateExpression('1+(2*3)')) //true
console.log(validateExpression('1+(2*3 + 9)')) //true
console.log(validateExpression('1+(2*3 + * 9)')) //false
console.log(validateExpression('(38+2L+3O+4Q4-2C-2*H-2-Q3)/10')) // true
console.log(validateExpression('(38+2L+3O+4Q4--2C-2*H-2-Q3)/10')) // false
console.log(validateExpression('(((((38))))+2)')) // true
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏