Hello.

There is such a picture: Regulars

And there is such a block as "string substitution". Explain what it is and how to use it. Something I do not really get, and examples or explanations about this I can not find.

  • one
    This is for the replacement operator, it is written in the second part of it “what to replace” and actually inserts in the indicated position what is indicated in this table. But to give at least some example you need to know in what language you have these regular programs, in order to understand how such an “operator” looks like. - Mike
  • @Mike thank you so much. I use Perl-compatible regular expressions. - dgd hsk
  • one
    Well, in the pearl syntax in the ABCD line, replacing s/A(.)(.)/$2-$&-$1-/ makes C-ABC-BD out of it ABC on what is said on the right side. D just stays where it is. he was "not found" - Mike

2 answers 2

String substitution is patterns in the replacement string, which are used to replace parts of the source text, taking into account regular expression matches.

To make it clearer: consider the usual function of replacing part of a string, for example PHP: str_replace

 $result = str_replace( "%body%", "black", "<body text='%body%'>"); // <body text='black'> 

Here the replacement of the text %body% text black occurred, but in the case of regular expressions we have not only the matched text, but also parts of the coincidence that carry the payload.

$0 - the whole match
$1 is the first group, $2 is the second group, etc.

Now the PHP example : preg_replace :

 $text = "<HTML><BODY> http://google.com </BODY></HTML>"; $result = preg_replace( "/http:\/\/(\\S+)/", "<A href='$0'>$1</A>", $text ); // <HTML><BODY> <A href='http://google.com'>google.com</A> </BODY></HTML> 

The regular expression coincided with the text http://google.com and it was replaced with the template <A href='$0'>$1</A> and the template contained matched groups.

The rest of the replacement patterns from the list provided in the question is not supported by most regular expression implementations, it is fully supported in Perl and partially in JavaScript.

    Explain what it is and how to use it.

    It's simple. In regular expressions, everything that is enclosed in parentheses ( ) is an “exciting” group, with the exception of “non-exciting” forward and backward scans . These groups can be referenced in the second part of the regexp replacing. There are many implementations of substitution in different languages.

    Perl example (replacing the first digit of the string with the number in quotes):

     $F = " 1234,hffffffff"; printf $F if ($F =~ s/(^\s*)(\d+)(.*$)/$1"$2"$3/s); 

    Conclusion:

      "1234",hffffffff 

    In this case, $ 1, $ 2, $ 3 - refer to the "captured" groups.

    • Thanks. Very informative. - dgd hsk