How to remove a number inside brackets at the end of string with regex
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?
You don't need the outer enclosing brackets. Try: str.replace(/\[\d\]$/, '');
If it is guaranteed that the string always contains a [number]
, you could just use substring
and lastIndexOf
:
str = str.substring(0, str.lastIndexOf('['));
Update: Or just add a test:
var index = str.lastIndexOf('[');
if(index > -1) {
str = str.substring(0,index);
}
\[\d+\]$
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+\]([^]]*)$
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 allow x
to be any number of digits -- if that's not what you want, remove the +
.
Here's the code:
import re
s = 'abc [1] [5] [2]'
while True:
new_s = re.sub(r'\[\d+\]([^]]*)$', r'\1', s)
if new_s == s:
break
s = new_s
print s
and the output:
abc [1] [5]
abc [1]
abc
/(.*)([\[].*[\]]\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.
精彩评论