简体   繁体   中英

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)/应该这样做,你需要使用匹配方法,它将在一个数组中提供两个组,一个具有您需要的字符串,另一个以其结尾。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM