VB.NET Update Mtext content with formating

VB.NET Update Mtext content with formating

Jedimaster
Collaborator Collaborator
1,639 Views
2 Replies
Message 1 of 3

VB.NET Update Mtext content with formating

Jedimaster
Collaborator
Collaborator

I have a VB.NET routine to find and replace text strings. I am snagging on formatted MTEXT

 

Case "AcDbMText"
Dim NewTextString As String = ""
Dim mtextObj As MText = trans.GetObject(selObj.ObjectId, OpenMode.ForWrite, False, True)
Dim OldTextString As String = mtextObj.Contents
NewTextString = Replace(OldTextString, CurrentFind, CurrentReplace, 1, -1, CompareMethod.Text)
If OldTextString <> NewTextString Then
mtextObj.Contents = NewTextString
End If
mtextObj.Dispose()

 

Right now the routine works a little too well, it replaces in formatting as well as the string. For instance if I replace "p" with "q" it takes out all the paragraph formatting under "\P". Is there a way to distinguish between actual visible and formatting. I was going to make an exceptions list but that would get rather lengthy and sticky especially when it comes to text styles.

0 Likes
Accepted solutions (1)
1,640 Views
2 Replies
Replies (2)
Message 2 of 3

_gile
Consultant
Consultant
Accepted solution

Hi,

 

Concerning the "\P" issue, you can simply replace back the newly created "\Q" with "\P":

 

mtext.Contents = mtext.Contents.Replace("P", "Q").Replace("\\Q", "\\P");

You can also use the unformated text returned by the MText.Text property tou build a replacing dictionary.

 

                var text = mtext.Text;
                var dict = new Dictionary<string, string>();
                foreach (var str in text.Split(' ', '\n', '\r'))
                {
                    if (str.Contains("P") && !dict.ContainsKey(str))
                        dict.Add(str, str.Replace('P', 'Q'));
                }

                var contents = mtext.Contents;
                foreach (var pair in dict)
                {
                    contents = contents.Replace(pair.Key, pair.Value);
                }

                mtext.Contents = contents;

You can also use regular expressions but I have no time right now to write an example.



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes
Message 3 of 3

_gile
Consultant
Consultant

Here's a Regex way:

 

mtext.Contents = Regex.Replace(mtext.Contents, @"(?i)(?<!\\)P", "Q");


Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes