Imports NXOpen
Imports System
Imports System.Collections.Generic
'' Renumber the all system expressions in workpart that match the specified regular expression
Module rename_system_expressions
Dim TS As Session
Dim LW As ListingWindow
Dim WP As Part
Sub Main(ByVal args() As String)
TS = Session.GetSession()
WP = TS.Parts.Work
LW = TS.ListingWindow
Dim systemRegularExpression = "p[0-9]+"
Dim pRegExp As Text.RegularExpressions.Regex = New Text.RegularExpressions.Regex(systemRegularExpression)
Dim temporaryRegularExpression As String = "_temp_[0-9]+"
Dim tmpRegExp As Text.RegularExpressions.Regex = New Text.RegularExpressions.Regex(temporaryRegularExpression)
Dim undoMark As Session.UndoMarkId = TS.SetUndoMark(Session.MarkVisibility.Visible, "Renumber System Expressions")
LW.Open()
LW.WriteLine("Processing Expressions")
Dim expDictionary As New SortedDictionary(Of String, Expression)
Dim expArray As Expression() = WP.Expressions.ToArray
'' find and give all matching expressions a temporary name
For ii As Integer = 0 To expArray.Length - 1
Dim exp As Expression = expArray(ii)
If pRegExp.IsMatch(exp.Name) Then
Dim matchExp As String = pRegExp.Match(exp.Name).ToString()
Dim pNumber As Integer = Text.RegularExpressions.Regex.Match(matchExp, "\d+").ToString()
Dim uniqueKey As String = pNumber.ToString.PadLeft(100, "0") + "-" + ii.ToString
Try
WP.Expressions.SystemRename(exp, exp.Name + "_temp_" + ii.ToString)
expDictionary.Add(uniqueKey, exp)
Catch ex As Exception
LW.WriteLine("Failed to rename " + exp.Name + " due to " + ex.Message)
End Try
End If
Next
'' Renumber the found expressions
Dim newNameCounter As Integer = 0
For Each pair As KeyValuePair(Of String, Expression) In expDictionary
Dim newName As String = "p" + newNameCounter.ToString
Dim oldName As String = tmpRegExp.Replace(pair.Value.Name, "")
Try
WP.Expressions.SystemRename(pair.Value, newName)
LW.WriteLine("Renamed " + oldName + " to " + newName)
newNameCounter += 1
Catch ex As Exception
LW.WriteLine("Failed to rename " + oldName + " with " + newName + " due to :" + ex.Message)
End Try
Next
TS.UpdateManager.DoUpdate(undoMark)
End Sub
End Module