Is there any method to find and replace text by using AutoLISP scripting?

2.2k Views Asked by At

I would like to programmatically to produce a code for AutoCAD using VBA. The code will find and replace text in the AutoCAD. I found that AutoLISP allow using script to call the command in AutoCAD. However, since "Find" command will induced the pop out windows so it cannot finish the process by the scripts (i.e. (command "Find" "text" "replace text")).

Is there any method to find and replace text by using AutoLISP scripting?

2

There are 2 best solutions below

0
On

Yes, vl-string-subst is the function. (vl-string-subst "Obi-wan" "Ben" "Ben Kenobi")

0
On

The specific command in AutoLsip that you're looking for is vl-string-subst. This however stops after it finds the first match in a string. If you want to go through the entire string and substitute every match, then Lee Mac has a simple solution for this problem. You'll probably need to add vl-load-com somewhere in the script to use vl-string-subst.

  • vl-string-subst documentation: Link 1
  • lv-load-com documentation: Link 2
  • Lee Mac's solution: Link 3
;;--------------------=={ String Subst }==--------------------;;
;;                                                            ;;
;;  Substitutes a string for all occurrences of another       ;;
;;  string within a string.                                   ;;
;;------------------------------------------------------------;;
;;  Author: Lee Mac, Copyright © 2011 - www.lee-mac.com       ;;
;;------------------------------------------------------------;;
;;  Arguments:                                                ;;
;;  new - string to be substituted for 'old'                  ;;
;;  old - string to be replaced                               ;;
;;  str - the string to be searched                           ;;
;;------------------------------------------------------------;;
;;  Returns:  String with 'old' replaced with 'new'           ;;
;;------------------------------------------------------------;;

(defun LM:StringSubst ( new old str / inc len )
    (setq len (strlen new)
          inc 0
    )
    (while (setq inc (vl-string-search old str inc))
        (setq str (vl-string-subst new old str inc)
              inc (+ inc len)
        )
    )
    str
)