Reputation: 2524
How can I replace contiguous substring of a string in C#? For example, the string
"<p>The quick fox</p>"
will be converted to
"<p>The quick fox</p>"
Upvotes: 2
Views: 295
Reputation: 49719
Let's call the original string s
and the substring subString
:
var s = "<p>The quick fox</p>";
var subString = " ";
I'd prefer this instead of a regex, much more readable:
var subStringTwice = subString + subString;
while (s.Contains(subStringTwice))
{
s = s.Replace(subStringTwice, subString);
}
Another possible solution with better performance:
var elements = s.Split(new []{subString}, StringSplitOptions.RemoveEmptyEntries);
s = string.Join(subString, elements);
// This part is only needed when subString can appear at the start or the end of s
if (result != "")
{
if (s.StartsWith(subString)) result = subString + result;
if (s.EndsWith(subString)) result = result + subString;
}
Upvotes: 2
Reputation: 12389
Maybe this simple one is enough:
( ){2,}
and replace with $1
(
that's captured in first parenthesized group)
See test at regex101
To check, if a substring is followed by itself, also can use a lookahead:
(?:( )(?=\1))+
and replace with empty. See test at regex101.com
Upvotes: 2
Reputation: 174706
Use the below regex
@"(.+)\1+"
(.+)
captures the group of characters and matches also the following \1+
one or more same set of characters.
And then replace the match with $1
string result = Regex.Replace(str, @"(.+)\1+", "$1");
Upvotes: 3