Regexp to capture string between delimiters

This sets the regular expression to capture the string between the delimiters:

Test: This is a test string [more or less]

Regexp: (?<=\[)(.*?)(?=\])

Returns: more or less

What if the string to be captured also contains delimiters?

Test 1: This is a test string [more [or] less]

Refund 1: more [or] less

Test 2: This is a test string [more [or [and] or] less]

Refund 2: more [or [and] or] less

And a few brackets?

Test 3: This is a test string [more [or [and] or] less] and [less [or [and] or] more]

Refund 3: more [or [and] or] less , less [or [and] or] more

What regular expression will do this? Or what little ruby ​​/ python script can do this?

+4
source share
1 answer

In javascript

 var str = 'This is a test string [more [or [and] or] less]'; str = str.match( /\[(.+)\]/ )[1]; // "more [or [and] or] less" 

Should you omit ? , .+ will greedily match the latter ] .

In python

 str = "This is a test string [more [or [and] or] less]" re.search( "(?<=\[).+(?=\])", str ).group() // "more [or [and] or] less" 

Refresh for multiple nested brackets

In javascript

 var matches = [], str = 'This is a test string [more [or [and] or] less] and [less [or [and] or] more] and [more]'; str.replace( /\[([^\]]*\[?[^\]]*\]?[^[]*)\]/g, function ( $0, $1 ) { $1 && matches.push( $1 ); }); console.log( matches ); // [ "more [or [and] or] less", "less [or [and] or] more", "more" ] 

In python

 import re str = 'This is a test string [more [or [and] or] less] and [less [or [and] or] more] and [more]' matches = re.findall( r'\[([^\]]*\[?[^\]]*\]?[^[]*)\]', str ) print matches # [ 'more [or [and] or] less', 'less [or [and] or] more', 'more' ] 
+6
source

All Articles