简体   繁体   中英

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

The regular expression you need to test your example string and output all words enclosed by square brackets would be /\\[([\\w]+)\\]/g

The [\\w]+ part selects all words comprised of alphanumeric characters. 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; 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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