[xsl] Replace the portion of text that matches pattern: XPath versus SNOBOL

Subject: [xsl] Replace the portion of text that matches pattern: XPath versus SNOBOL
From: "Roger L Costello costello@xxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Sat, 22 Mar 2025 12:03:15 -0000
Sometimes you want to search for occurrences of a pattern in text and replace
those substrings that match the pattern. For example, suppose WORD holds the
text, "BAT" and we want to search for the pattern 'A' and replace it with 'E.'
In XPath use the replace() function. The following XPath looks for the pattern
'A' in WORD and replaces the matched 'A' with 'E':

replace($WORD, 'A', 'E')  <-- returns "BET"

Important point: $WORD is unchanged. Its value is still "BAT."

Here's how replace is done in SNOBOL:

WORD 'A' = 'E'

Important point: WORD is changed. The value of WORD is now "BET."

Suppose the text contains more than one substring that matches the pattern,
and we want to replace all matching occurrences. For example, suppose WORD
holds the text, "BALANCE" and we want to search for the pattern 'A' and
replace each match with 'E.' By default, the XPath replace() function replaces
all occurrences:

replace($WORD,' A', 'E')  <-- returns "BELENCE"

To repeat, WORD is unchanged. The value of WORD is still "BALANCE."

SNOBOL only replaces the first occurrence. To replace all occurrences, do a
loop:

LOOP WORD 'A' = 'E'			:S(LOOP)

The replacement statement is labelled with LOOP. The part on the right-side
means, "If the replacement succeeds (S means Succeeds), then goto LOOP." In
other words, repeatedly perform the replacement until there are no more
matches.

To repeat, WORD is changed. Now the value of WORD is "BELENCE."

Suppose that you want to only replace the first match, i.e., we want
"BELANCE." I do not think that there is any way to configure the XPath
replace() function to "Replace only the first match." Please correct me if I
am wrong about this.

Recap:
-	In XPath, use replace( WORD, pattern, replacement )
-	In SNOBOL, use WORD pattern = replacement
-	The XPath replace() function does not change WORD
-	In SNOBOL, the value of WORD is changed
-	In XPath, the replace() function replaces each occurrence of pattern with
replacement
-	In SNOBOL only the first occurrence is replaced. Use a loop to replace all
occurrences
-	In XPath, there is no way to configure the replace() function to only
replace the first occurrence

Lesson Learned; When designing a new programming language, consider the
options for pattern matching replacement; the options are nicely illustrated
by comparing XPath and SNOBOL.

Current Thread