用特定内容替换自定义括号

我试图将{all-content} ^ {^}替换为 hat {all-content} 。 字符串和预期的输出应该像...

|---------------------|-------------------|-------------------|
|    String Input     |  Expected Result  |     What I get    |
|---------------------|-------------------|-------------------|
|        {A}^{^}      |     hat{A}       |       hat{A}     |
|---------------------|-------------------|-------------------|
|   {{A}_{22}}^{^}    |  hat{{A}_{22}}   |   hat{{A}_{22}}  |
|---------------------|-------------------|-------------------|
| {A}_{X-1} {B+2}^{^} |{A}_{X-1} hat{B+2}|hat{A}_{X-1} {B+2}|
|---------------------|-------------------|-------------------|
|   {A+{B}^{^}}^{^}   | hat{A+hat{B}}   | hat{A+{B}}^{^}   |
|---------------------|-------------------|-------------------|

这是正则表达式..

str = str.replace(/{(.*?)}^{^}/g, "hat{$1}")

str = '{A}^{^} this is sample content {{A}_{22}}^{^} with more complex structure {A}_{X-1} {B+2}^{^} another content with multi level content {A+{B}^{^}}^{^}';
str = str.replace(/{(.*?)}^{^}/g, "hat{$1}");
console.log(str)

试试这个代码,并不完美,因为它假定每个匹配包含相同数量的^{^}{但应该在大多数情况下工作:

let re = /{.*?}[^s]+/g;
let text = "{A}^{^} this is sample content {{A}_{22}}^{^} with more complex structure {A}_{X-1} {B+2}^{^} another content with multi level content {A+{B}^{^}}^{^}";

text.match(re).map(m => {  
  let replacement = m;
  
  replacement = replacement.replace(/^{^}/g, "");
  replacement = replacement.replace(/{/g, "hat{");
  
  text = text.replace(m, replacement);
});

console.log(text);

如果我正确地理解你的问题,那就是懒惰的量词不是在正确的方向上懒散。

在字符串{A}_{X-1} {B+2}^{^}您想要抓住{A} _ {X-1} {B + 2} ^ {^},但它会看到起始括号和需要{A} _ {X-1} {B + 2} ^ {^}

一种解决方法是禁止{在字符串中,像这样:

{([^{]*?)}^{^}

或者,如果你想禁止任何空格字符,它也可以工作。

链接地址: http://www.djcxy.com/p/59517.html

上一篇: Replace custom brackets with specific content

下一篇: How can I replace specifc characters only within a substring in powershell