简体   繁体   English

如何使用正则表达式检查单词是否带有括号

[英]How can I check if a word has parentheses using regular expression

I'm trying to separate the words that has "[]" brackets around them, for example this line 我正在尝试将方括号内包含“ []”的单词分开,例如以下行

"I hate [running] and [sweating]" how can i use regular expression just to check if a word is wrapped around "running" or "sweating" or any word. “我讨厌[运行中]和[冒汗]”如何使用正则表达式只是为了检查是否在“运行中”或“冒汗”或任何单词周围包裹了一个单词。

I tried this. 我试过了 but it didn't work. 但这没用。

if(data.word === /[ ]/){}

Here is the expression needed : 这是所需的表达式:

/\[([^\[\]]+)\]/

so going by your example we would apply it as the following: 因此,以您的示例为例,我们将其应用如下:

"I hate [running] and [sweating]".match(/\\[([^\\[\\]]+)\\]/g) which will result in the words with the braces , same could be applied on a single word , and we could check whether it match or not to determine if it is surrounded by square brackets "I hate [running] and [sweating]".match(/\\[([^\\[\\]]+)\\]/g)这将导致带有大括号的单词,同样可以应用于单个单词,我们可以检查它是否匹配,以确定它是否被方括号包围

The regular expression you need to test your example string and output all words enclosed by square brackets would be /\\[([\\w]+)\\]/g 您需要测试示例字符串并输出所有用方括号括起来的单词的正则表达式为/\\[([\\w]+)\\]/g

The [\\w]+ part selects all words comprised of alphanumeric characters. [\\w]+部分选择由字母数字字符组成的所有单词。 Including \\[ and \\] explicitly matches the square brackets around those words. 包括\\[\\]明确匹配这些单词周围的方括号。 The parentheses ( and ) enclose the pattern that describes which parts should be returned. 括号()包围了描述应返回哪些部分的模式。

I can highly recommend regex101.com as a handy playground for trying our regular expressions; 我强烈建议将regex101.com用作方便的游乐场,以尝试使用我们的正则表达式; it's the first place I went when writing the regular expression above to check for accuracy. 这是我编写上面的正则表达式检查准确性时去过的第一位。

An example of how to implement this can be seen here . 在此处可以看到如何实现此功能的示例。

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

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