regular expressions can not only find text patterns but can also substitute new text in place of those patterns the sub(method for regex objects is passed two arguments the first argument is string to replace any matches the second is the string for the regular expression the sub(method returns string with the substitutions applied for exampleenter the following into the interactive shellnamesregex re compile( 'agent \ +'namesregex sub('censored''agent alice gave the secret documents to agent bob ''censored gave the secret documents to censored sometimes you may need to use the matched text itself as part of the substitution in the first argument to sub()you can type \ \ \ and so onto mean "enter the text of group and so onin the substitution for examplesay you want to censor the names of the secret agents by showing just the first letters of their names to do thisyou could use the regex agent (\ )\wand pass '\ ****as the first argument to sub(the \ in that string will be replaced by whatever text was matched by group -that isthe (\wgroup of the regular expression agentnamesregex re compile( 'agent (\ )\ *'agentnamesregex sub( '\ ****''agent alice told agent carol that agent eve knew agent bob was double agent ' ***told ***that ***knew ***was double agent managing complex regexes regular expressions are fine if the text pattern you need to match is simple but matching complicated text patterns might require longconvoluted regular expressions you can mitigate this by telling the re compile(function to ignore whitespace and comments inside the regular expression string this "verbose modecan be enabled by passing the variable re verbose as the second argument to re compile(now instead of hard-to-read regular expression like thisphoneregex re compile( '((\ { }|\(\ { }\))?(\ |-|)?\ { }(\ |-|)\ { (\ *(ext| |ext )\ *\ { , })?)'you can spread the regular expression over multiple lines with comments like thisphoneregex re compile( '''(\ { }|\(\ { }\))(\ |-|)\ { (\ |-|\ { area code separator first digits separator last digits