简体   繁体   English

如何使用正则表达式删除字符串末尾括号内的数字

[英]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]'. 希望有一个递归函数,它接受一个字符串并删除结尾'[x]'。 For example 'abc [1] [3]' needs to be 'abc [1]'. 例如'abc [1] [3]'需要是'abc [1]'。 The string could also be 'abc [1] [5] [2]' and would need to be 'abc [1] [5]'. 该字符串也可以是'abc [1] [5] [2]',并且需要是'abc [1] [5]'。

I'm trying str.replace(/[\\\\\\[\\d\\\\\\]]$/, '') but it only replaces the very last closing bracket and ignores everything else. 我正在尝试str.replace(/[\\\\\\[\\d\\\\\\]]$/, '')但它只替换最后一个结束括号并忽略其他所有内容。

Any ideas? 有任何想法吗?

You don't need the outer enclosing brackets. 您不需要外部封闭支架。 Try: str.replace(/\\[\\d\\]$/, ''); 尝试: str.replace(/\\[\\d\\]$/, '');

If it is guaranteed that the string always contains a [number] , you could just use substring and lastIndexOf : 如果保证字符串始终包含[number] ,则可以使用substringlastIndexOf

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. 我说“应该”,因为我仍然不像我想要的那样精通正则表达式,但是在regexr(用于测试正则表达式的一个漂亮的小AIR应用程序)中,它似乎有效。

EDIT: 编辑:

Just in case anybody wants to play around with regexr, it's at http://gskinner.com/RegExr/desktop/ . 如果有人想玩regexr,请访问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. \\[\\d+\\]([^]]*)$适用于Python,应该可以在Javascript中运行。 This allows for trailing bits after the [x] , which are left behind. 这允许在[x]之后的尾随位,这些位留下。 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 + . 另请注意,我更改了正则表达式以允许x为任意数量的数字 - 如果这不是您想要的,请删除+

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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