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

时间:2017-04-24 07:24:26

标签: javascript regex

我试图将 {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)




更新: {...} - >可以是任何字符,特殊字符或unicode符号。也可能包含多个级别的嵌套花括号。

正则表达式有可能吗?如果没有,任何其他选择..

2 个答案:

答案 0 :(得分:0)

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



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




答案 1 :(得分:-1)

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

在字符串{A}_{X-1} {B+2}^{^}中,您要抓住{A} _ {X-1} {B + 2} ^ {^} ,但它会看到开头的括号,并且需要 {A} _ {X-1} {B + 2} ^ {^}

一种解决方案是禁止字符串中的{,如下所示:

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

或者,如果你想禁止任何空白字符,它也会有效。

相关问题