How to put similar named objects into collection in python? I wrote a script that can detect similar objects based on the selected objects but can't put them in a collection named after selected objects.
It's not working.

import bpy 

selected_objects = bpy.context.selected_objects

for selected_object in selected_objects:
    name = selected_object.name
    collections = bpy.data.collections.new(name)
    bpy.context.scene.collection.children.link(collections)
    bpy.ops.object.select_pattern(pattern=f"*{name}*")
    objs = bpy.context.selected_objects
    coll = bpy.data.collections[name]

    for obj in objs:
        cols = obj.users_collection
        coll.objects.link(obj)
        for col in cols:
        col.objects.unlink(obj)


I want from:

To:
I would do the same in python that I could do in the UI, which is to use Select Pattern, and then move these selected items to a Collection.
In python:
bpy.ops.object.select_all( action='DESELECT' ) # Deselect all objects
bpy.ops.object.select_pattern(pattern=&quot;Sphere*&quot;)

# if collection Sphere does not yet exist:
bpy.ops.object.move_to_collection( collection_index=0, is_new=True, new_collection_name='Sphere' ) # new collection
# else if collection Sphere does exist:
bpy.ops.object.move_to_collection( collection_index=2 ) # need collection index