How do I use Regex to replace characters in string?

Just started using Construct 2? Post your questions here

Post » Fri Jan 08, 2016 1:38 am

I'm trying to learn how to use regex effectively to find and replace characters/strings.

For example, I would like to replace all the "p" (lower case) with "*" in the string "Peter Piper picked a peck of pickled peppers".

Using RegexReplace(Text.Text,"p","","*") only replaces the first p with *. Shouldn't this expression match every "p" in the string?

When I run RegexMatchCount(Text.Text,"p",""), again I only get 1 match, when I would expect to get 7.

I found a workaround where I add the condition "While RegexMatchCount(Text.Text,"p","")!=0" and it will run until there are no more "p" to change, but this way seems like a bit of a hack to me.

I am also familiar with the alternative option using the replace expression: replace(Text.Text,"p","*"), but I feel like Regex could give me much more control in more complex scenarios, such as case sensitivity for this example.

References:
Construct 2 System Expressions https://www.scirra.com/manual/126/system-expressions
IndieKiwi Regex Tutorial https://www.scirra.com/tutorials/1337/e ... t-2/page-1


Capx:

https://www.dropbox.com/s/wd8dlg2hbx3vb ... .capx?dl=0
Mistakes were made.
B
47
S
23
G
101
Posts: 1,538
Reputation: 57,067

Post » Sat Jan 09, 2016 12:16 am

You have to set the global flag ("g") for all matches.

Code: Select all
RegexReplace(Text.Text, "p", "g", "*")
B
55
S
28
G
18
Posts: 1,520
Reputation: 25,305

Post » Sat Jan 09, 2016 1:35 am

Great that did the trick! Didn't see that flag mentioned in the tutorial. Now that I look closely at the examples, I see that loops were to get the multiple matches.

Thanks much!
Mistakes were made.
B
47
S
23
G
101
Posts: 1,538
Reputation: 57,067


Return to Beginner's Questions

Who is online

Users browsing this forum: No registered users and 1 guest