我试图将{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符号。也可能包含多个级别的嵌套花括号。
那么在正则表达式中可能吗?如果没有,任何其他选择..
用**字样**说,开头“{...}”内容的规则是什么。 –
{...}将以[tex](https://en.wikipedia.org/wiki/TeX)格式显示...一般来说,包含特殊字符和Unicode符号的任何字符 – mimind
因为第四个示例需要通过嵌套方式进行递归结构中,JavaScript的正则表达式无法自行完成。你需要更复杂的解析。 –