在以下字符串中:

(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.

推荐答案

我认为目前不能用Javascript中的正则表达式以一般方式解决这个问题,因为不能递归地匹配平衡括号.

就我个人而言,我会将文本拆分为组成字符,构建括号组,然后用一些逻辑将所有内容重新连接起来.例如:

let text = '(10+10)*2*((1+1)*1)√(16)+(12*12)+2';
let changedText = '';
let parts = text.split('');
let parCount = null;
let group = '';
let groups = [];

// Group the original text into nested parentheses and other characters.
for (let i = 0; i < parts.length; i++) {
    // Keep a track of parentheses nesting; if parCount is larger than 0,
    // then there are unclosed parentheses left in the current group.
    if (parts[i] == '(') parCount++;
    if (parts[i] == ')') parCount--;

    group += parts[i];

    // Add every group of balanced parens or single characters.
    if (parCount === 0 && group !== '') {
        groups.push(group);
        group = '';
    }
}

// Join groups, while replacing the root character and surrounding groups
// with the nthroot() syntax.
for (let i = 0; i < groups.length; i++) {
    let isRoot = i < groups.length - 2 && groups[i + 1] == '√';
    let hasParGroups = groups[i][0] == '(' && groups[i + 2][0] == '(';

    // If the next group is a root symbol surrounded by parenthesized groups,
    // join them using the nthroot() syntax.
    if (isRoot && hasParGroups) {
        let stripped = groups[i + 2].replace(/^\(|\)$/g, '');
        changedText += `nthroot(${stripped}, ${groups[i]})`;
        // Skip groups that belong to root.
        i = i + 2;
    } else {
        // Append non-root groups.
        changedText += groups[i]
    }
}

console.log('Before:', text, '\n', 'After:', changedText);

但并不是说它很漂亮

Javascript相关问答推荐

可以将SuperTest导入为ES 6模块吗?

Regex可以 Select 以任何顺序匹配组

在JavaScript中,如何将请求的回调函数的结果合并到运行的代码中?

在Vite React库中添加子模块路径

实现JS代码更改CSS元素

Chart.js-显示值应该在其中的引用区域

闭包是将值复制到内存的另一个位置吗?

将数组扩展到对象中

如何在JAVASCRIPT中合并两组对象并返回一些键

TypeError:无法读取未定义的属性(正在读取';宽度';)

Next.js中的服务器端组件列表筛选

警告框不显示包含HTML输入字段的总和

FireBase云函数-函数外部的ENV变量

将嵌套数组的元素乘以其深度,输出一个和

如何在Java脚本中对数据进行签名,并在PHP中验证签名?

Socket.IO在刷新页面时执行函数两次

如何在独立的Angular 应用程序中添加Lucide-Angel?

AG-GRIDreact 显示布尔值而不是复选框

无法使用npm install安装react-dom、react和next

如何在Reaction中清除输入字段