如何删除括号中除完全数字内容之外的所有内容?
我想获取一个字符串并删除方括号内所有出现的字符:
[foo]
、[foo123bar]
和 [123bar]
应该被删除
但我想保持所有仅由数字组成的括号完整:
[1]
和 [123]
应该保留
我已经尝试了一些方法,但无济于事:
text = text.replace(/\[^[0-9+]\]/gi, "");
text = text.replace(/\[^[\d]\]/gi, "");
I want to take a string and remove all occurrences of characters within square brackets:
[foo]
, [foo123bar]
, and [123bar]
should be removed
But I want to keep intact any brackets consisting of only numbers:
[1]
and [123]
should remain
I've tried a couple of things, to no avail:
text = text.replace(/\[^[0-9+]\]/gi, "");
text = text.replace(/\[^[\d]\]/gi, "");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找的工具是负向预测。使用方法如下:
\[
找到左括号后,先行查找(?!\d+\])
断言括号不仅仅包含数字。然后,
[^\[\]]+
匹配任何非方括号的内容,确保(例如)您不会意外匹配“嵌套”括号,例如[[123]]
。最后,
\]
匹配右括号。The tool you're looking for is negative lookahead. Here's how you would use it:
After
\[
locates an opening bracket, the lookahead,(?!\d+\])
asserts that the brackets do not contain only digits.Then,
[^\[\]]+
matches anything that's not square brackets, ensuring (for example) that you don't accidentally match "nested" brackets, like[[123]]
.Finally,
\]
matches the closing bracket.您可能需要这个:
说明:您希望将这些序列保留在仅包含数字的括号内。另一种说法是删除那些 1) 括在方括号内、2) 不包含右方括号以及 3) 包含至少一个非数字字符的序列。上面的正则表达式匹配左括号 (
\[
),后跟除右括号 ([^\]]
之外的任意字符序列,请注意,右括号有要转义),然后是一个非数字字符(也不包括右括号),然后是除右括号之外的任意字符序列,然后是右括号。You probably need this:
Explanation: you want to keep those sequences within brackets that contain only numbers. An alternative way to say this is to delete those sequences that are 1) enclosed within brackets, 2) contain no closing bracket and 3) contain at least one non-numeric character. The above regex matches an opening bracket (
\[
), followed by an arbitrary sequence of characters except the closing bracket ([^\]]
, note that the closing bracket had to be escaped), then a non-numeric character (also excluding the closing bracket), then an arbitrary sequence of characters except the closing bracket, then the closing bracket.在Python中:
In python: