var input = "---Three dashes a-b-c-d";
Regex to get
var output = "- - - Three dashes a-b-c-d";
and Regex get back to original, added spaces are deleted at the beginning. output => input
Code without Regex input => output
var input = "---Three dashes a-b-c-d";
var output = "";
var i = 0;
while (i < input.Length && input[i] == '-')
{
output += "- ";
i++;
}
output += input.Substring(i);
While @TedLyngmo's solution works, it is rather inefficient with a wild card in the lookbehind pattern.
A more efficient approach would be to use a positive lookbehind pattern to assert that only dashes precede a match:
@"(?<=^-+)"
And substitute the match with a space.
On regex101, the above regex took 0.2ms to run while @TedLyngmo's took 19.5ms.
Demo: https://regex101.com/r/6uy1K8/3
Regex (with a trailing space) to remove the added spaces to get back the original:
@"(?<=^(?:- )*-) "
Note the space at the end
And substitute the match with nothing.
On regex101, the above regex took 0.3ms to run while @TedLyngmo's took 28.1ms.
Demo: https://regex101.com/r/fBOirM/3
Note that the desired behaviors require a regex engine that supports variable-width lookbehind, which C# happens to have. The above regexes are otherwise not portable to platforms that do not have such a support.
One way could be a negative lookbehind to check that no character before a dash to add a space too is anything but a dash:
@"(?<![^-].*)-"
(?<!
- start of negative lookbehind
[^-]
- any character but -
.*
- zero or more of any character)
- end of negative lookbehind-
- a literal -
Match globally and substitute with -
(dash + space)
Demo
Removing the added spaces to get the original back could be done in a similar way:
@"(?<![^- ].*)- "
Match globally and substitute with -
(dash).
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With