简体   繁体   English

如何删除双括号中的字符串?

[英]How to remove string in double brackets?

I want to know how can I remove the string in double brackets & including brackets. 我想知道如何删除双括号和包括括号中的字符串。 Here's an example 这是一个例子

var str="(C84) [Yayui (shirogisu)] 1 Day with the Commodore";
var n = str.replace(/\s*\(.*?\)\s*/g, '')
alert(n);

So far it only removed single brackets but not the one with brackets inside another bracket. 到目前为止,它只删除了一个括号,而没有删除一个在另一个括号内的括号。 The final output should look like this: 最终输出应如下所示:

1 Day with the Commodore

How can I remove the string in any type of brackets such as {,},[,],(,) Live version: http://jsfiddle.net/aPa25/ 如何删除任何类型的括号中的字符串,例如{,},[,],(,)实时版本: http : //jsfiddle.net/aPa25/

Not sure what you mean by double brackets, but to remove all the stuff in both parens and square braces you could use 不确定双括号的含义,但是要删除括号和方括号中的所有内容,您可以使用

str.replace(/\s*\(.*?\)\s*/g, '').replace(/\s*\[.*\]\s*/g, '')

The first replace removes everything in parentheses, the second removes everything in square braces. 第一个replace删除括号中的所有内容,第二个replace删除方括号中的所有内容。

Additionally, if you know the form of your input is always going to be like that, ie a parenthetical part followed by a square braced part, you could just do: 另外,如果您知道输入的形式总是这样,即括号部分后跟方括号部分,您可以这样做:

str.replace(/^\s*\(\w+\)\s*\[.*\]\s*/, '')

It's less general but might be more robust if that assumption is true. 它的通用性较低,但如果该假设为真,则可能会更健壮。

EDIT: Given that there can be other paren and square braces later in the text that you want to keep, try: 编辑:鉴于以后您想要保留的文本中可能还有其他括号和方括号,请尝试:

str.replace(/\s*\([^)]*\)\s*/g, '').replace(/\s*\[[^\]]*\]\s*/g, '')

If you say there can be square braces nested within the first square braces, I will say that, mathematically, you will require a more powerful theoretical machine than a finite state machine (regex). 如果您说在第一个方括号内可以嵌套方括号,那么我会说,从数学上讲,您将需要比有限状态机(regex)更强大的理论机。

This should work as the replace regex. 这应该用作替换正则表达式。 It looks individually for each of the bracket types. 它针对每种括号类型进行单独查找。

\s*(?:\[[^[]+]|\([^)]+\)|{[^}]+})\s*

Edit: I think the "nesting order" needs to be the same as in the regex, so it may require re-ordering of the alternation if what I have is wrong. 编辑:我认为“嵌套顺序”必须与正则表达式中的相同,因此如果我输入的内容有误,则可能需要对交替进行重新排序。 However, it does work on your examples. 但是,它确实适用于您的示例。

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

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