I'm not sure if this can be done with regular expressions. Here is a script that will do what you need in case of a repeated word called pattern .
It moves through the characters of a string named str , trying to match another string with the name pattern . If the match fails, the pattern string expands as needed.
EDIT . I made the code more compact.
str = 'lullabylullabylullaby'; pattern = str(1); matchingState = false; sPtr = 1; pPtr = 1; while sPtr <= length(str) if str(sPtr) == pattern(pPtr) %// if match succeeds, keep looping through pattern string matchingState = true; pPtr = pPtr + 1; pPtr = mod(pPtr-1,length(pattern)) + 1; else %// if match fails, extend pattern string and start again if matchingState sPtr = sPtr - 1; %// don't change str index when transitioning out of matching state end matchingState = false; pattern = str(1:sPtr); pPtr = 1; end sPtr = sPtr + 1; end display(pattern);
Conclusion:
pattern = lullaby
Note:
This does not allow arbitrary delimiters between occurrences of the pattern string. For example, if str = 'lullaby1lullaby2lullaby1lullaby2'; then
pattern = lullaby1lullaby2
It also allows the pattern end in the middle of the loop without changing the result. For example, str = 'lullaby1lullaby2lullaby1'; still lead to
pattern = lullaby1lullaby2
To fix this, you can add lines
if pPtr ~= length(pattern) pattern = str; end
source share