gpt4 book ai didi

javascript - 正则表达式获取两个字符之间的文本?

转载 作者:行者123 更新时间:2023-11-29 23:54:40 25 4
gpt4 key购买 nike

我想替换正斜杠之后和不包括字符的结束括号之前的文本。

My text: 
<h3>notThisText/IWantToReplaceThis)<h3>

$('h3').text($('h3').text().replace(regEx, 'textReplaced'));

Wanted result after replace:
notThisText/textReplaced)

我试过了

regex = /([^\/]+$)+/ //replaces the parantheses as well 
regex = \/([^\)]+) //replaces the slash as well

但正如您在我的评论中看到的那样,这些都不排除斜杠和结束括号。有人可以帮忙吗?

最佳答案

类似 /(?<=\/)[^)]+(?=\))/ 的模式不会在 JS 中工作,因为它的正则表达式引擎不支持 lookbehind 构造。因此,您应该使用以下解决方案之一:

s.replace(/(\/)[^)]+(\))/, '$1textReplaced$2')
s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')
s.replace(/(\/)[^)]+/, '$1textReplaced')
s.replace(/\/[^)]+\)/, '/textReplaced)')

(...)形成一个可以用 $ 引用的捕获组+ number,一个反向引用,来自替换模式。第一个解决方案是消耗 /) , 并将它们放入捕获组中。如果您需要匹配连续的、重叠的匹配项,请使用第二种解决方案 ( s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced') )。如果)最后不需要,第三个解决方案(replace(/(\/)[^)]+/, '$1textReplaced'))就可以了。最后一个解决方案 ( s.replace(/\/[^)]+\)/, '/textReplaced)') ) 将工作如果 /)是事先已知的静态值。

关于javascript - 正则表达式获取两个字符之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41955894/

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