Regular expression to extract text between square

2018-12-31 04:41发布

Simple regex question. I have a string on the following format:

this is a [sample] string with [some] special words. [another one]

What is the regular expression to extract the words within the square brackets, ie.

sample
some
another one

Note: In my use case, brackets cannot be nested.

标签: regex
7条回答
无与为乐者.
2楼-- · 2018-12-31 05:20

This should work out ok:

\[([^]]+)\]
查看更多
荒废的爱情
3楼-- · 2018-12-31 05:28
(?<=\[).+?(?=\])

Will capture content without brackets

  • (?<=\[) - positive lookbehind for [

  • .*? - non greedy match for the content

  • (?=\]) - positive lookahead for ]

EDIT: for nested brackets the below regex should work:

(\[(?:\[??[^\[]*?\]))
查看更多
泪湿衣
4楼-- · 2018-12-31 05:29

Can brackets be nested?

If not: \[([^]]+)\] matches one item, including square brackets. Backreference \1 will contain the item to be match. If your regex flavor supports lookaround, use

(?<=\[)[^]]+(?=\])

This will only match the item inside brackets.

查看更多
何处买醉
5楼-- · 2018-12-31 05:29

(?<=\().*?(?=\)) works good as per explanation given above. Here's a Python example:

import re 
str =    "Pagination.go('formPagination_bottom',2,'Page',true,'1',null,'2013')"
re.search('(?<=\().*?(?=\))', str).group()
"'formPagination_bottom',2,'Page',true,'1',null,'2013'"
查看更多
明月照影归
6楼-- · 2018-12-31 05:29

This code will extract the content between square brackets and parentheses

(?:(?<=\().+?(?=\))|(?<=\[).+?(?=\]))

(?: non capturing group
(?<=\().+?(?=\)) positive lookbehind and lookahead to extract the text between parentheses
| or
(?<=\[).+?(?=\]) positive lookbehind and lookahead to extract the text between square brackets
查看更多
琉璃瓶的回忆
7楼-- · 2018-12-31 05:40
([[][a-z \s]+[]])

Above should work given the following explaination

  • characters within square brackets[] defines characte class which means pattern should match atleast one charcater mentioned within square brackets

  • \s specifies a space

  •  + means atleast one of the character mentioned previously to +.

查看更多
登录 后发表回答