How do I replace only the first occurence of a string?

Get help using Construct 2

Post » Fri Sep 18, 2015 6:36 pm

I want to replace a word by another one in a long text. I can use the "replace" system expression but it replace all occurence of my string in the whole text.

Someone here know a trick to replace only the first occurence?

Thanks in advance!
I made 2 games so far: www.ID-Games.net
B
10
S
2
Posts: 54
Reputation: 1,373

Post » Fri Sep 18, 2015 6:53 pm

It's a bit long but you can use text.find("txt_to_replace") to find the index of the 1st occurence, then use left() and right() to build the new string with the replaced word.
example : if you want to replace "txt" by "text" in a random string called "string":

string = left(string , string.find("txt") & "text" & right(string, len(string)-string.find("txt")-3)
B
8
S
1
Posts: 76
Reputation: 628

Post » Fri Sep 18, 2015 11:05 pm

Image
B
64
S
23
G
7
Posts: 1,481
Reputation: 10,823

Post » Fri Sep 25, 2015 1:07 pm

Thanks for the reply guys!

@korbaach: That's exactly what I need! I read about regexreplace and didn't understand exactly how to use it by reading the manual. You capx will help me a lot! Thanks for taking the time to do it!
I made 2 games so far: www.ID-Games.net
B
10
S
2
Posts: 54
Reputation: 1,373

Post » Fri Sep 25, 2015 1:17 pm

Just to add to my previous reply, the documentation for the regexreplace says:

RegexReplace(String, Regex, Flags, Replace)
In String substitute matches for the regular expression Regex (with Flags) with the string Replace. The replacement string can contain the following special characters: $$ (inserts a $), $& (inserts the matched substring), $` (inserts the portion of the string that precedes the matched substring), or $' (inserts the portion of the string that follows the matched substring).


...but it didn't explain what exactly is regex and what is the flag. I suppose that this is coming from another langage so I'll google it...in your example korbaach you use "m" as a flag and I can reproduce it but I like to know what every thing in my code means. :)

Thanks again!
I made 2 games so far: www.ID-Games.net
B
10
S
2
Posts: 54
Reputation: 1,373

Post » Fri Sep 25, 2015 3:08 pm

Isn't this covered in the RegEx Documentation on W3Schools site?
If your vision so exceeds your ability, then look to something closer.
Moderator
B
131
S
29
G
81
Posts: 5,328
Reputation: 56,630


Return to How do I....?

Who is online

Users browsing this forum: adamebastin, Bro7hers, korbaach, plinkie and 8 guests