regex - Extract all words from string except words in square brackets -


again i'm totally stuck in creating regular expression.

i have string pattern like:

str = ' worda [] wordab [xyz] wordabc [x] '

so there word followed in brackets [ ... ] or empty brackets []. length of words, leading , trailing white spaces , number of chars inside brackets random. random how sequence repeated.

i'd extract words without brackets:

output =       'worda'    'wordbc'    'wordabc' 

i think problem square brackets functional characters regular expressions. tried like

output = regexp(str,'^\[.+\]$','split') 

and variations without success.

any hints?

we can select words using \w+ regex. select words (include ones in brackets). words outside of brackets have spaces before , after them, can add positive lookbehind (?<=\s) - sure there space before word, , positive lookahead (?=\s) - sure there space after word. additionally first word doesn't have space before it, need include condition include start of string well, giving positive lookbehind (?<=\s|^). have full regex:

(?<=\s|^)\w+(?=\s) 

regular expression visualization

in case if can have worda[] string (no spaces), need add [ positive lookahead.

(?<=\s|^)\w+(?=\s|\[) 

regular expression visualization

in case if can have worda [ xyz ] strings (spaces within brackets), above regex wouldn't work , need different strategy - find words not having [ before. cannot words without [ before them, because match yz in [xyz], need need words not leaded [ , symbols other ].

(?<!\[[^]]*)\w+ 

regular expression visualization


Comments

Popular posts from this blog

Why can rails not find a route created by a helper? -

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -