maya python How can I enter a regular expression for search from the created text field?
import maya.cmds as cmds
import re
def search_objects_by_regex(*args):
# テキストフィールドから正規表現を取得
regex_pattern = cmds.textField("regexField", query=True, text=True)
# シーン内のすべてのオブジェクトを取得
all_objects = cmds.ls()
# 正規表現パターンをコンパイル
try:
regex = re.compile(regex_pattern)
except re.error as e:
cmds.warning(f"Invalid regex pattern: {e}")
return
# 正規表現に一致するオブジェクトをフィルタリング
matching_objects = [obj for obj in all_objects if regex.search(obj)]
# 結果を表示
if matching_objects:
cmds.confirmDialog(title='Search Results', message='\n'.join(matching_objects))
else:
cmds.confirmDialog(title='Search Results', message='No matching objects found.')
# UIの作成
if cmds.window("regexSearchWindow", exists=True):
cmds.deleteUI("regexSearchWindow")
cmds.window("regexSearchWindow", title="Regex Search", widthHeight=(300, 100))
cmds.columnLayout(adjustableColumn=True)
cmds.text(label="Enter Regex Pattern:")
cmds.textField("regexField")
cmds.button(label="Search", command=search_objects_by_regex)
cmds.showWindow("regexSearchWindow")
検索置換の場合
import maya.cmds as cmds
import re
def replace_objects_by_regex(*args):
# テキストフィールドから正規表現と置換文字列を取得
regex_pattern = cmds.textField("regexField", query=True, text=True)
replace_text = cmds.textField("replaceField", query=True, text=True)
# シーン内のすべてのオブジェクトを取得
all_objects = cmds.ls()
# 正規表現パターンをコンパイル
try:
regex = re.compile(regex_pattern)
except re.error as e:
cmds.warning(f"Invalid regex pattern: {e}")
return
# 正規表現に一致するオブジェクトを置換
replaced_objects = [regex.sub(replace_text, obj) for obj in all_objects]
# 結果を表示
if replaced_objects:
cmds.confirmDialog(title='Replace Results', message='\n'.join(replaced_objects))
else:
cmds.confirmDialog(title='Replace Results', message='No objects replaced.')
# UIの作成
if cmds.window("regexReplaceWindow", exists=True):
cmds.deleteUI("regexReplaceWindow")
cmds.window("regexReplaceWindow", title="Regex Replace", widthHeight=(300, 150))
cmds.columnLayout(adjustableColumn=True)
cmds.text(label="Enter Regex Pattern:")
cmds.textField("regexField")
cmds.text(label="Enter Replace Text:")
cmds.textField("replaceField")
cmds.button(label="Replace", command=replace_objects_by_regex)
cmds.showWindow("regexReplaceWindow")