Sunday 15 May 2011

regex - get all but last occurrences of a pattern in javascript -



regex - get all but last occurrences of a pattern in javascript -

given next patterns:

"profile[foreclosure_defenses_attributes][0][some_text]" "something[something_else_attributes][0][hello_attributes][0][other_stuff]"

i able extract lastly part using non-capturing groups:

var regex = /(?:\w+(\[\w+\]\[\d+\])+)(\[\w+\])/; str = "profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]"; match = regex.exec(str); ["profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]", "[properties_attributes][0]", "[other_stuff]"]

however, want able lastly part. in other words, [some_text] or [other_stuff].

i cannot figure out how noncapturing groups. how else can accomplish this?

something like?

shorter, , matches if can have more of [] items. var regex = /(.*)(?:\[\w+\])$/; var = "something[something_else_attributes][0][hello_attributes][0][other_stuff11][other_stuff22][other_stuff33][other_stuff44]".match(regex)[1]; a;

or using replace, though less performant.

var regex = /(.*)(?:\[\w+\])$/; var = "something[something_else_attributes][0][hello_attributes][0][other_stuff11][other_stuff22][other_stuff33][other_stuff44]".replace(regex, function(_,$1){ homecoming $1}); a;

javascript regex

No comments:

Post a Comment