gpt4 book ai didi

javascript - RegExp 仅查找第一个括号内的字符串?

转载 作者:行者123 更新时间:2023-12-03 05:19:51 25 4
gpt4 key购买 nike

例如字符串中:

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)

最佳答案

射击答案:正则表达式单独无法解决这个问题

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

您可以这样做

//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))

关于javascript - RegExp 仅查找第一个括号内的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41442527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com