I'm trying to move all occurrences of a particular pattern to the beginning of a string. For example, if the pattern is **'pat'** then I'd like to my regex substitution to convert

> 
> 'a pat b pat c pat d'
> 
> 
> 

to

> 
> 'pat pat pat a b c d'
> 
> 
> 

I could achieve this by repeatedly applying 

```
string <- gsub(x=string,pattern='(.*)(pat )(.*)',replacement='\\2\\1\\3')

```

to my initial string value, but this requires looping over the string an arbitrary number of times since I do not know how many times to expect the pattern to occur in the string. I also cannot simply take a greedy approach, such as applying the substitution as many times as the length of the string, since I am working with extremely long vectors of strings of varying length and applying vector substitutions.

So, is there any way to achieve this functionality with a single regex expression?

**EDIT**

The consensus appears to be that this cannot be done with a single regex/gsub expression. I should provide more details on why exactly this is what is needed for me when other solutions would do in more restricted cases:

I am working with a large dataset (millions of rows) containing a string field on which I wish to perform cleaning rules. These rules consist of a list of regex replacements specified in a separate file; there are a few hundred of these. The cleaning process proceeds by looping over the regex rules and applying each to the entire string column through the vectorized version of `gsub`.

For some of these rules, but not all, I would like to identify all instances of a specific pattern, then move all such instances to the beginning of the string. The specified pattern will change from one rule to the other, and so no solution which leverages the particulars of the sought pattern are tenable. 

It's looking like I can't achieve my goal without some serious restructuring of the process, unless anyone has any clever ideas ...