RegExReplace glitch... Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
kunkel321
Posts: 1057
Joined: 30 Nov 2015, 21:19

RegExReplace glitch...

15 May 2021, 16:26

Hi Folks,
My regex here seems to work some of the time when testing this small block of code. It seems to always fail in my larger code though...

Code: Select all

MyEntry := "They uses the following. They reads often."
MyEntry := RegExReplace(MyEntry, "([Tt]hey\s)(.*)(s)", "$1$2")
MsgBox post fix:  %MyEntry%
It's supposed to do a simple grammar fix: Change uses > use and reads > read. Oddly, when I test it, it usually changes reads but not uses. Any ideas what I've done wrong?

EDIT: Note also, that this one DOES work

Code: Select all

MsgBox % RegExReplace("They uses the book", "([Tt]hey\s)(.*)(s)", "$1$2")
This would seem to be functionally identical -- yes?

EDIT2: Nope... If I swap the haystack strings, then the error follows the longer string... So I guess my regex likes the shorter one, but not the longer one.
ste(phen|ve) kunkel
User avatar
mikeyww
Posts: 26936
Joined: 09 Sep 2014, 18:38

Re: RegExReplace glitch...  Topic is solved

15 May 2021, 16:43

The regex "expands" by default. It is called "greedy"-- eating up as many characters as possible, while maintaining a match. The following would work.

Code: Select all

MyEntry := RegExReplace(MyEntry, "i)they \w+\Ks\b")
Or the "lazy" approach, which finds the "shortest" match:

Code: Select all

MyEntry := RegExReplace(MyEntry, "([Tt]hey\s)(.*?)s\b", "$1$2")
The "?" after the wildcard (*) tells the parser to be lazy.
User avatar
kunkel321
Posts: 1057
Joined: 30 Nov 2015, 21:19

Re: RegExReplace glitch...

15 May 2021, 17:02

Ah yes, of course... It was matching everything between the first "They" and the last word ending in "s." Thanks Mike! 8-)
ste(phen|ve) kunkel

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: filipemb, Google [Bot], mikeyww and 187 guests