简体   繁体   中英

Regular expression to select single words inside parentheses using stringr

I specified that I'm using stringr because its character escaping is not "standard" regex escaping.

I want to detect strings that have a single word inside parentheses. Thus, I want to detect

"Men's shirt (blue)"

and not detect

"Blade Runner (Director's cut)"

If it helps simplify the regex, all the parenthetical parts are always at the end of the string.

I have attempted

str_detect(my_string, "\\(\\w?\\)") which yields no results and

str_detect(my_string, "\\(\\S\\)$") which returns everything including multiple words

as well as various combinations using //S, with or without the $, etc.

When I look for other stack overflow answers, I usually find slightly different questions whose answers are simply "use this:" along with what seems like an incomprehensible regex using lookaheads and other seemilgly too-complicated things. I thank you for a little explanation on why the (probably obvious and simple) regex works.

Looks like I didn't hit upon the //S+ in my combinations. I was checking for a single non-space character, not one or more non-space characters. This solution works:

str_detect(desc, "\\(\\S+\\)$")

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-2025 STACKOOM.COM