Notifications
Clear all

[Closed] Find and replace a string question?

Hi,does anyboy know about this question,I want to find some special string and replace them via maxscript,below is example:

A txt file include lines below:

…other strings…
line01=“I_like_3dsmax”
line02=“I_like_3dsmax_of_course”
…other strings…

when I reading a txt file include many lines,the line01 is what I want to find(“I_like_3dsmax”),but the line02 has the same part (“I_like_3dsmax”),if I use findsting function:

--while reading txt not end loop
(
--aa=readline  some txt file (aa maybe is "I_like_3dsmax" or "I_like_3dsmax_of_course")
if findstring aa "I_like_3dsmax" !=undefined then substituteString aa "3dsmax" "photoshop"
)

the result will be:
“I_like_photoshop”
“I_like_photoshop_of_course”

what I want avoid is “I_like_3dsmax_of_course” may still not change,below is correct:
“I_like_photoshop”
“I_like_3dsmax_of_course”

so how to fix it?

4 Replies

For this very specific situation, where you want to replace a complete quoted string, you could do:

findstring str "\"I_like_3dsmax\""

Otherwise, for more advanced search/replace functionalities you would need to use RegEx.

1 Reply
(@momo2012)
Joined: 11 months ago

Posts: 0

Hi Jorge,you mean

findstring "I_like_3dsmax" "\"I_like_3dsmax\""

the result is undefined,am I wrong?

In the example you showed, you are using: line01=“I_like_3dsmax”
I assumed that it is the result of the returned line.

Or you just added the ‘line01=’ part to show us that it is the line 1 in your file?

Here is a function to replace all matching words in a stream:

(
	fn ReplaceWords mStream mFromStr mToStr mIgnoreCase:false =
	(
		regex = dotnetclass "system.text.regularexpressions.regex"
		pattern = "\b" + mFromStr + "\b"
		if mIgnoreCase do pattern = "(?i)" + pattern
		
		result = regex.replace mStream pattern mToStr
		return (result as stringstream)
	)


	/* Test */
	stream = stringstream ""
	format "car card car cardboard car
" to:stream
	format "carnival cardinals car
" to:stream
	print stream
	
	ReplaceWords stream "car" "BALL" mIgnoreCase:true
)