Improve capture group logic