问题描述
我需要一个正则表达式来删除括号之间的最后一个表达式(也有括号)
I need a regex to remove last expression between brackets (also with brackets)
来源:输入[东西][东西2]目标:输入[东西]
source: input[something][something2]target: input[something]
我试过这个,但它删除了所有两个:
I've tried this, but it removes all two:
"input[something][something2]".replace(/\[.*?\]/g, '');
推荐答案
请注意 \[.*?\]$
将不起作用,因为它将匹配 first [
(因为正则表达式引擎从左到右处理字符串),然后将匹配字符串的所有其余部分,直到其末尾的 ]
.因此,它将匹配 input[something][something2]
中的 [something][something2]
.
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]
.
您可以指定字符串锚点的结尾并使用[^\][]*
(匹配除[
和] 之外的零个或多个字符)
code>) 而不是 .*?
:
You may specify the end of string anchor and use [^\][]*
(matching zero or more chars other than [
and ]
) instead of .*?
:
\[[^\][]*]$
查看 JS 演示:
console.log(
"input[something][something2]".replace(/\[[^\][]*]$/, '')
);
详情:
\[
- 文字[
[^\][]*
- 除了[
和]
之外的零个或多个字符]
- 文字]
$
- 字符串结束
\[
- 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')
);
这里,$1
是对使用 (.*)
子模式捕获的值的反向引用.但是,它的工作方式会有所不同,因为它将返回字符串中最后一个 [
之前的所有内容,然后所有之后的 [
包括括号将被删除.
Here, $1
is the backreference to the value captured with (.*)
subpattern. 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.
这篇关于删除字符串末尾方括号之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!