summaryrefslogtreecommitdiffstats
path: root/Functions/Misc
diff options
context:
space:
mode:
authorStephane Chazelas <stephane.chazelas@gmail.com>2021-09-06 14:43:01 -0700
committerBart Schaefer <schaefer@ipost.com>2021-09-06 14:43:01 -0700
commitbb61da36aaeeaa70413cdf5bc66d7a71194f93e5 (patch)
tree4fa62b5e09077ddee7988a2e89fda4154bfd458b /Functions/Misc
parent49154: clarify status on exec failure (diff)
downloadzsh-bb61da36aaeeaa70413cdf5bc66d7a71194f93e5.tar
zsh-bb61da36aaeeaa70413cdf5bc66d7a71194f93e5.tar.gz
zsh-bb61da36aaeeaa70413cdf5bc66d7a71194f93e5.tar.bz2
zsh-bb61da36aaeeaa70413cdf5bc66d7a71194f93e5.tar.lz
zsh-bb61da36aaeeaa70413cdf5bc66d7a71194f93e5.tar.xz
zsh-bb61da36aaeeaa70413cdf5bc66d7a71194f93e5.tar.zst
zsh-bb61da36aaeeaa70413cdf5bc66d7a71194f93e5.zip
45180: clarify doc for POSIX EREs, fix an issue with PCRE when the replacement was empty or generated more than one element
Diffstat (limited to 'Functions/Misc')
-rw-r--r--Functions/Misc/regexp-replace98
1 files changed, 73 insertions, 25 deletions
diff --git a/Functions/Misc/regexp-replace b/Functions/Misc/regexp-replace
index dec105524..0d5948075 100644
--- a/Functions/Misc/regexp-replace
+++ b/Functions/Misc/regexp-replace
@@ -8,36 +8,84 @@
# $ and backtick substitutions; in particular, $MATCH will be replaced
# by the portion of the string matched by the regular expression.
-integer pcre
+# we use positional parameters instead of variables to avoid
+# clashing with the user's variable. Make sure we start with 3 and only
+# 3 elements:
+argv=("$1" "$2" "$3")
-[[ -o re_match_pcre ]] && pcre=1
+# $4 records whether pcre is enabled as that information would otherwise
+# be lost after emulate -L zsh
+4=0
+[[ -o re_match_pcre ]] && 4=1
emulate -L zsh
-(( pcre )) && setopt re_match_pcre
-# $4 is the string to be matched
-4=${(P)1}
-# $5 is the final string
-5=
-# 6 indicates if we made a change
-6=
+
local MATCH MBEGIN MEND
local -a match mbegin mend
-while [[ -n $4 ]]; do
- if [[ $4 =~ $2 ]]; then
- # append initial part and subsituted match
- 5+=${4[1,MBEGIN-1]}${(e)3}
- # truncate remaining string
- 4=${4[MEND+1,-1]}
- # indicate we did something
- 6=1
- else
- break
- fi
-done
-5+=$4
+if (( $4 )); then
+ # if using pcre, we're using pcre_match and a running offset
+ # That's needed for ^, \A, \b, and look-behind operators to work
+ # properly.
+
+ zmodload zsh/pcre || return 2
+ pcre_compile -- "$2" && pcre_study || return 2
+
+ # $4 is the current *byte* offset, $5, $6 reserved for later use
+ 4=0 6=
+
+ local ZPCRE_OP
+ while pcre_match -b -n $4 -- "${(P)1}"; do
+ # append offsets and computed replacement to the array
+ # we need to perform the evaluation in a scalar assignment so that if
+ # it generates an array, the elements are converted to string (by
+ # joining with the first chararacter of $IFS as usual)