如何删除括号中除完全数字内容之外的所有内容?

发布于 2024-11-27 19:12:23 字数 329 浏览 1 评论 0原文

我想获取一个字符串并删除方括号内所有出现的字符:

[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我还不会笑 2024-12-04 19:12:23

您正在寻找的工具是负向预测。使用方法如下:

text = text.replace(/\[(?!\d+\])[^\[\]]+\]/g, "");

\[ 找到左括号后,先行查找 (?!\d+\]) 断言括号不仅仅包含数字。

然后, [^\[\]]+ 匹配任何非方括号的内容,确保(例如)您不会意外匹配“嵌套”括号,例如 [[123]]

最后,\] 匹配右括号。

The tool you're looking for is negative lookahead. Here's how you would use it:

text = text.replace(/\[(?!\d+\])[^\[\]]+\]/g, "");

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.

谎言月老 2024-12-04 19:12:23

您可能需要这个:

text = text.replace(/\[[^\]]*[^0-9\]][^\]]*\]/gi, "");

说明:您希望将这些序列保留在仅包含数字的括号内。另一种说法是删除那些 1) 括在方括号内、2) 不包含右方括号以及 3) 包含至少一个非数字字符的序列。上面的正则表达式匹配左括号 (\[),后跟除右括号 ([^\]] 之外的任意字符序列,请注意,右括号有要转义),然后是一个非数字字符(也不包括右括号),然后是除右括号之外的任意字符序列,然后是右括号。

You probably need this:

text = text.replace(/\[[^\]]*[^0-9\]][^\]]*\]/gi, "");

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.

萌逼全场 2024-12-04 19:12:23

在Python中:

import re
text = '[foo] [foo123bar] [123bar] [foo123] [1] [123]'
print re.sub('(\[.*[^0-9]+\])|(\[[^0-9][^\]]*\])', '', text)

In python:

import re
text = '[foo] [foo123bar] [123bar] [foo123] [1] [123]'
print re.sub('(\[.*[^0-9]+\])|(\[[^0-9][^\]]*\])', '', text)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文