简体   繁体   English

正则表达式查找方括号内的单个单词

[英]Regex to find single word surrounded by square brackets

I'm stumped on the following regex problem. 我对以下正则表达式问题感到困惑。

I'm trying to find single words surrounded by square brackets without spaces. 我正在尝试找到被方括号括起来且没有空格的单词。 Like this: 像这样:

[singleWord]

I don't want to find phrases, like this 我不想找到这样的短语

[a series of words]

At the moment I'm using this regex: 目前,我正在使用此正则表达式:

/\[(.*?)\]/g

It's finding words and phrases. 它正在寻找单词短语。 Can anyone suggest how to modify it so that it only finds words in square brackets without spaces? 谁能建议如何修改它,使其只能在方括号中找到没有空格的单词?

Thanks!! 谢谢!!

Try replacing .*? 尝试替换.*? with \\S* in your regex. 在您的正则表达式中使用\\S* . will match any character including spaces, whereas \\S will match only non-space characters 将匹配包括空格在内的任何字符,而\\S仅匹配非空格字符

/\[(\S*)\]/g

I'm trying to find single words surrounded by square brackets without spaces.

您可以使用此正则表达式:

/\[([^\s\]]*)\]/g

You current regex allows anything. 您当前的正则表达式允许任何操作。 You only want letters. 你只想要字母。

/\[([a-z])\]/gi

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

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