[solved] (simple) RegExReplace replaces too many occurrences Topic is solved

Get help with using AutoHotkey and its commands and hotkeys
User avatar
Posts: 271
Joined: 12 Mar 2014, 10:09

[solved] (simple) RegExReplace replaces too many occurrences

06 Apr 2019, 10:58

Why does my RegExReplace here replaces two RN's instead of just one?

Code: Select all

Var := "Jack`r`n`r`n`r`n"
MsgBox % """" . DisplayRandN(Var) . """" ; shows "JackRNRNRN"
Var := RegExReplace(Var, "(\r\n)$", "")
MsgBox % """" . DisplayRandN(Var) . """"  ; shows "JackRN" - Why only one "RN" ?

stretch := StrReplace(stretch, "`r", "R")
stretch := StrReplace(stretch, "`n", "N")
return stretch
Last edited by Benny-D on 06 Apr 2019, 19:50, edited 1 time in total.
User avatar
Posts: 56
Joined: 08 Mar 2019, 16:39

Re: (simple) RegExReplace replaces too many occurrences  Topic is solved

06 Apr 2019, 13:08

PCRE wrote:The dollar character is an assertion that is true only if the current
matching point is at the end of the subject string, or immediately
before a newline at the end of the string (by default). Note, however,
that it does not actually match the newline. Dollar need not be the
last character of the pattern if a number of alternatives are involved,
but it should be the last item in any branch in which it appears. Dol-
lar has no special meaning in a character class.

The meaning of dollar can be changed so that it matches only at the
very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at
compile time. This does not affect the \Z assertion.
The default newline character sequence is \r\n. The first time around (\r\n)$ matches the second set of newline characters because the latter condition has been fulfilled: ^Jack`r`n`r`n`r`n$. The matched set is then erased: ^Jack`r`n|`r`n$ (pipe denotes the matching head's position). Since at this point characters yet to be consumed remain, the engine runs them against the pattern once more. This time (\r\n)$ matches the third (or after the erasure, the second, if you will) set of newline characters: ^Jack`r`n`r`n$. The former condition has been fulfilled for the true end-of-string has been encountered. The matched set of newline characters are erased and RegExp execution ceases: ^Jack`r`n|$.

To resolve this either:
  1. Redefine the how the default newline character sequence is to be interpreted. Compile with `n) or `r).
  2. Alter the behavior of $ (PCRE_DOLLAR_ENDONLY). Compile with D).

Return to “Ask For Help”

Who is online

Users browsing this forum: Dlxgp7, Jstenoien, Sintrias, Smile_ and 58 guests