删除字符串开头和结尾的方括号

新手上路,请多包涵

如果方括号存在,我想从字符串的开头和结尾删除方括号。

 [Just a string]
Just a string
Just a string [comment]
[Just a string [comment]]

应该导致

Just a string
Just a string
Just a string [comment]
Just a string [comment]

我试图构建一个正则表达式,但我没有以正确的方式得到它,因为它没有寻找位置:

 string.replace(/[\[\]]+/g,'')

原文由 user3142695 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答
string.replace(/^\[(.+)\]$/,'$1')

应该做的伎俩。

  • ^ 匹配字符串的开头
  • $ 匹配字符串的结尾。
  • (.+) 匹配两者之间的所有内容,以在最终字符串中报告。

原文由 blue112 发布,翻译遵循 CC BY-SA 3.0 许可协议

Blue112 提供了一个解决方案,用于从 一行 的开头/结尾删除 [] (如果两者都存在)。

要删除 []字符串 的开头/结尾(如果两者都存在)你需要

input.replace(/^\[([\s\S]*)]$/,'$1')

或者

input.replace(/^\[([^]*)]$/,'$1')

In JS, to match any symbol including a newline, you either use [\s\S] (or [\w\W] or [\d\D] ), or [^] that matches任何 _非无_。

 var s = "[word  \n[line]]";
console.log(s.replace(/^\[([\s\S]*)]$/, "$1"));

原文由 Wiktor Stribiżew 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题