Search code examples
regexpcre

Regex Replacement Syntax for number of replacent group occurences


Take the sample string:

__________Hello

I want to replace lines starting with 10 x _ with 20 x _

Desired output:

____________________Hello

I can do this a number of ways, i.e:

/^(_{10})/\1\1/
/^_{10}/____________________/
/^(__________)/\1\1/
etc...

Question:

Is there a way within the regex specification/expression itself - say PCRE (or any regex library/engine for that matter) - to specify the replacement occurence of a character ?

For example:

/_{10}/_{20}/

I don't know if I'm having a mind blank or if I've just never done this, but I cannot seem to find any such thing in the regex specification docs.


Solution

  • It can't be done within the Regex itself.

    If I have the input "39572a4872" and I want to replace it with "39572aaaaa4872", there are many simple ways to achieve that, which can include Regular expressions, but as Wiktor explained in the comment thread, the actual quantifier of the replacement is not something itself that is achieved through regex.

    It may seem unimportant, since in this example I could simply just apply the replacement 5 times manually or programatically, but one of the benefits of standardized technologies is applying the same concepts in different environments, languages, even within programs.

    I as well as many others have had a lot of success with the portability of my regex because of this.

    This question was to see if specifying quantifiers for replacement strings was possible within the syntax of a regex itself. Which it is surely not.