Replace match with Stringtheory

Hi Carlos

well that’s a coincidence - I wrote code to do this over the weekend and just yesterday sent it to Bruce for consideration for inclusion in a future version of ST along with a bunch of other stuff.

I called the new method ReplaceSlice and the comment in the code says:

!----------------------------------------------------------------------------------
! Sets the value of the specified region within the string to the passed string.
! Unlike setSlice() which either truncates or space fills the new value to fit the
! existing size of the slice, replaceSlice() will expand or contract the slice
! within the value string to exactly fit the newValue.

if you scroll down the in code at

you will see some code of the form:

 st.replace(st.slice(srcStart,srcEnd),'replacementString',1,srcStart,srcEnd)

actually the final parameter is redundant and it could have just been written:

 st.replace(st.slice(srcStart,srcEnd),'replacementString',1,srcStart)

with the new method replaceSlice this would instead look like:

 st.replaceSlice(srcStart,srcEnd,'replacementString')

and would be more efficient as it is not doing a “dummy search” before the replace.

as regards your current code

  st.FindMatchPosition(regex,starts,ends,Match:Regular,TRUE)
  IF starts AND ends 
    st.SetValue( st.Slice(1,starts-1) & createnewvalue() & st.Slice(ends+1) )
  END

I suggest changing the test so instead have

  st.FindMatchPosition(regex,starts,ends,Match:Regular,TRUE)
  IF starts AND ends >= starts
    st.SetValue( st.Slice(1,starts-1) & createnewvalue() & st.Slice(ends+1) )
  END

or use the replace code with a dummy search which might be a little faster:

IF starts AND ends >= starts 
  st.replace(st.slice(starts,ends),createnewvalue(),1,starts)
END

then if/when replaceSlice becomes available, instead use:

IF starts AND ends >= starts 
 st.replaceSlice(starts,ends,createnewvalue())
END

if you are keen to try replaceSlice now then (if Bruce is agreeable) I could send you my current version by PM.

one thing to note is that your st.FindMatchPosition will find the SMALLEST minimal match.

hopefully that is what you are after (and not the maximal “leftmost longest” match).

if you are after that “leftmost longest” match, have a look at the code here which includes StrPosAndLen which returns position and minimum and maximum length of string matched against regex There are a lot of “gotchas” with strPos and this works around them.

hth and cheers

Geoff R

1 Like