如何提取特定字符前后嵌套括号的内容?
在以下字符串中:
(10+10)*2*((1+1)*1)√(16)+(12*12)+2
我尝试将 ((1+1)*1)√(16)
替换为 nthroot(16,(1+1)*1)
。
具体来说,我想提取 √
两侧第一组括号中的所有内容。
括号本身可以包含多层括号和许多不同的符号。
语言是JavaScript。
我尝试了一些类似
但我学习正则表达式的每一次尝试都失败了,我无法弄清楚这一点。
In the following string:
(10+10)*2*((1+1)*1)√(16)+(12*12)+2
I am trying replace ((1+1)*1)√(16)
with nthroot(16,(1+1)*1)
.
Specifically, I want to extract everything in the first sets of brackets on each side of the √
.
The brackets themselves could contain many layers of brackets and many different symbols.
Language is JavaScript.
I tried a couple things like <str>.replace(/\((.+)\)√\((.+)\)/g, 'nthroot($1,$2)')
but every one of my attempts at learning RegEx fails and I can't figure this out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您目前无法使用 Javascript 中的正则表达式以通用方式解决此问题,因为您无法递归地匹配平衡括号。
就我个人而言,我会通过将文本拆分为其组成字符,构建括号组,然后用某种逻辑将所有内容重新连接在一起来解决此问题。例如:
不过也不敢说它漂亮。 ;)
I don't think you can currently solve this in a general way with a regular expression in Javascript, since you can't match balanced parentheses recursively.
Personally, I'd approach this by splitting the text into its constituent characters, building groups of parentheses, and joining all back together with some logic. For example:
Not saying it's pretty, though. ;)
解析任务,就像OP所要求的那样,不能仅用正则表达式来涵盖。
特别是令牌对嵌套括号的正确解析需要一个简单且无正则表达式的自定义解析过程。更重要的是,对于OP的用例,需要从左侧和右侧标记(由
√
分隔的标记)中分别解析正确/有效的括号表达式)。一种可能的方法可以基于单个 <代码>分割/
减少
与一些专门的辅助函数的协作任务...Parsing tasks, like what the OP is asking for, can not be covered by a regular expression alone.
Especially a token's correct parsing for nested parentheses needs a simple and regex free custom parsing process. Even more, as for the OP's use case one needs to parse a correct/valid parenthesized expression each from a left and a right hand-side token (the ones that are/were separated by
√
).A possible approach could be based on a single
split
/reduce
task with the collaboration of some specialized helper functions ...