RegExp只在第一个括号内找到字符串?

时间:2017-01-03 11:30:38

标签: javascript

对于字符串中的示例:

create or replace procedure SYSPROC.Q2SPJ016(
p_SLNO in INTEGER,
p_HIRE_DATE in DATE,
p_BUSINESS_GROUP in VARCHAR(25)
)

期望的输出:

p_SLNO in INTEGER,
p_HIRE_DATE in DATE,
p_BUSINESS_GROUP in VARCHAR(25)

1 个答案:

答案 0 :(得分:1)

拍摄答案正则表达式单靠无法解决此问题

正则表达式是作业的错误工具,因为您正在处理嵌套结构,即递归。您可以使用正则表达式和堆栈来执行此操作

您可以这样做

//function that matches outer most paranthesis
function matchOuterBracket(str) {
  let re = /\(|\)/gi
  let stack = []
  let startI = -1,
    endI = -1
  while (match = re.exec(str)) {
    if (match[0] == '(') {
      stack.push(match.index)
    } else {
      startI = stack.pop()
    }
    if (stack.length == 0) {
      endI = match.index
      break
    }
  }
  if (startI == undefined ||
    startI == -1 ||
    endI == -1 ||
    endI == undefined) {
    return ""
  }
  return str.slice(startI +1 , endI)
}


//testing

var str = `create or replace procedure SYSPROC.Q2SPJ016(
p_SLNO in INTEGER,
p_HIRE_DATE in DATE,
p_BUSINESS_GROUP in VARCHAR(25)
)`
console.log(matchOuterBracket(str))