简体   繁体   English

删除字符串末尾方括号之间的文本

[英]Remove text between square brackets at the end of string

I need a regex to remove last expression between brackets (also with brackets) 我需要一个正则表达式来删除括号之间的最后一个表达式(也带有括号)

source: input[something][something2] target: input[something] 来源:input [something] [something2]目标:input [something]

I've tried this, but it removes all two: 我已经尝试过了,但是删除了所有两个:

"input[something][something2]".replace(/\[.*?\]/g, '');

Note that \\[.*?\\]$ won't work as it will match the first [ (because a regex engine processes the string from left to right), and then will match all the rest of the string up to the ] at its end. 请注意\\[.*?\\]$将不起作用,因为它将匹配第一个 [ (因为正则表达式引擎从左到右处理该字符串),然后将匹配其余所有字符串,直到位于]它的结束。 So, it will match [something][something2] in input[something][something2] . 因此,它将匹配[something][something2]input[something][something2]

You may specify the end of string anchor and use [^\\][]* (matching zero or more chars other than [ and ] ) instead of .*? 您可以指定字符串锚点的结尾,并使用[^\\][]* (匹配[]以外的零个或多个字符)代替.*? :

\[[^\][]*]$

See the JS demo: 参见JS演示:

 console.log( "input[something][something2]".replace(/\\[[^\\][]*]$/, '') ); 

Details : 详细资料

  • \\[ - a literal [ \\[ -文字[
  • [^\\][]* - zero or more chars other than [ and ] [^\\][]* -除[]以外的零个或多个字符
  • ] - a literal ] ] -文字]
  • $ - end of string $ -字符串结尾

Another way is to use .* at the start of the pattern to grab the whole line, capture it, and the let it backtrack to get the last [...] : 另一种方法是在模式的开头使用.*来抓取整行,捕获它,然后让它回溯以获取最后的[...]

 console.log( "input[something][something2]".replace(/^(.*)\\[.*]$/, '$1') ); 

Here, $1 is the backreference to the value captured with (.*) subpattern. 在这里, $1是对使用(.*)子模式捕获的值的后向引用。 However, it will work a bit differently, since it will return all up to the last [ in the string, and then all after that [ including the bracket will get removed. 但是,它的工作方式会有所不同,因为它将返回字符串中的最后一个[ ,然后删除所有之后的[包括括号]。

不要使用g修饰符,而应使用$锚点:

"input[something][something2]".replace(/\[[^\]]*\]$/, '');

try this code 试试这个代码

 var str = "Hello, this is Mike (example)"; alert(str.replace(/\\s*\\(.*?\\)\\s*/g, '')); 

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

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