如何使用正则表达式删除字符串末尾括号内的数字
寻找一个递归函数,它接受一个字符串并删除结尾的“[x]”。例如“abc [1] [3]”需要是“abc [1]”。该字符串也可以是“abc [1] [5] [2]”,并且需要是“abc [1] [5]”。
我正在尝试 str.replace(/[\\\[\d\\\]]$/, '')
但它只替换最后一个右括号并忽略其他所有内容。
有什么想法吗?
Looking to have a recursive function that takes a string and removes the ending '[x]'. For example 'abc [1] [3]' needs to be 'abc [1]'. The string could also be 'abc [1] [5] [2]' and would need to be 'abc [1] [5]'.
I'm trying str.replace(/[\\\[\d\\\]]$/, '')
but it only replaces the very last closing bracket and ignores everything else.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不需要外部括号。尝试:
str.replace(/\[\d\]$/, '');
You don't need the outer enclosing brackets. Try:
str.replace(/\[\d\]$/, '');
如果保证字符串始终包含
[number]
,则可以使用子字符串
和lastIndexOf
:更新: 或者只是添加一个测试:
If it is guaranteed that the string always contains a
[number]
, you could just usesubstring
andlastIndexOf
:Update: Or just add a test:
应该说任何括号后跟任意数量的数字,后跟括号,全部位于字符串的末尾。
我说“应该”是因为我仍然没有像我希望的那样精通正则表达式,但在 regexr(一个用于测试正则表达式的漂亮的小型 AIR 应用程序)中,它似乎有效。
编辑:
以防万一有人想使用 regexr,它位于 http://gskinner.com/RegExr/desktop /。我与它没有任何关系,我只是认为它是一个很好的工具。
that should say any bracket followed by any number of digits followed by a bracket, all at the end of the string.
I say "should" because I'm still not as proficient at regex as I'd like to be, but in regexr (a nifty little AIR app for testing regular expressions), it seems to work.
EDIT:
Just in case anybody wants to play around with regexr, it's at http://gskinner.com/RegExr/desktop/. I have no affiliation with it, I just think it's a nice tool to have.
\[\d+\]([^]]*)$
在 Python 中工作并且应该在 Javascript 中工作。这允许在[x]
之后留下尾随位。我相信这就是您没有看到预期结果的原因,因为您留下了尾随空格。另请注意,我更改了正则表达式以允许x
为任意位数 - 如果这不是您想要的,请删除+
。这是代码:
和输出:
\[\d+\]([^]]*)$
works in Python and should work in Javascript. This allows for trailing bits after the[x]
, which are left behind. I believe that's why you weren't seeing the expected results, because you left trailing whitespace behind. Also note that I changed the regex to allowx
to be any number of digits -- if that's not what you want, remove the+
.Here's the code:
and the output:
/(.*)([\[].*[\]]\Z)/
应该做到这一点,您将需要使用匹配方法来做到这一点,并且它将在一个数组,一个包含所需的字符串,另一个包含结尾。/(.*)([\[].*[\]]\Z)/
should do it, you will need to do it using a match method, and it will provide two groups in an array, one with your required string, and the other with the ending in it.