Replace custom brackets with specific content

I'm trying to replace {all-content}^{^} into hat{all-content} . And the string and expected output should be like ...

|---------------------|-------------------|-------------------|
|    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}}^{^}   |
|---------------------|-------------------|-------------------|

Here is the regex ..

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

If I understand your problem correctly, it's that the lazy quantifier isn't lazy in the right direction.

in the string {A}_{X-1} {B+2}^{^} you want to catch {A}_{X-1} {B+2}^{^} but it sees the beginning brackets and takes {A}_{X-1} {B+2}^{^} .

One solution is to disallow { in the string, like this:

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

or, if you want to disallow any white space characters it would also work.

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

上一篇: 如何解决Java Erorr消息

下一篇: 用特定内容替换自定义括号