Substitute Method

Applies to TestComplete 15.47, last modified on January 20, 2023

Description

The RegExpr.Substitute method returns the ATemplate string where the special characters are replaced with text that matches the regular expression or it’s part:

Character Replaced with
$& A text matching the whole regular expression.
$0 A text matching the whole regular expression.
$nn (where nn is a non-zero positive integer) A text matching the nn-th sub-expression.

To place a dollar sign that should not be treated as a special character use \$: 'The price is $& \$.'

To place a digit right after the $nn delimit nn with curly braces '{}': 'a${1}2bc'

Declaration

RegExprObj.Substitute(ATemplate)

RegExprObj An expression, variable or parameter that specifies a reference to a RegExpr object
ATemplate [in]    Required    String    
Result String

Applies To

The method is applied to the following object:

Parameters

The method has the following parameter:

ATemplate

Specifies the text template.

Result Value

The string with substituted text.

Remarks

You should call the Exec, ExecNext or ExecPos method before calling the Substitute method to define the matching text.

Example

This sample code illustrates how to use this method. It extracts the phone number and parses it into sub-groups.

DelphiScript

procedure SubstituteSample;
var
  MyRegExp: OleVariant;
  ResStr: String;
begin
  MyRegExp:=HISUtils.RegExpr;
  ResStr:='';

  //This expression specifies a phone number pattern
  MyRegExp.Expression:='(\+\d *)?(\(\d+\) *)?(\d+(-\d*)*)';
  if MyRegExp.Exec('Jack, when you arrive, phone me +1(234)567-89-01.') then
    ResStr := MyRegExp.Substitute('The phone number $& consists of these parts:'+#13
    +'Zone code $1, city code $2 and number itself $3.');
  Log.Message(ResStr);
  //Posts the following to the log:
  //'The phone number +1(234)567-89-01 consists of these parts:
  // Zone code +1, city code (234) and number itself 567-89-01.'
end;

See Also

Using Regular Expressions in Scripts
Using Regular Expressions in Scripts
Expression Property
InputString Property
Exec Method
Replace Method

Highlight search results