Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to add space to each dash at the beginning of string

Tags:

c#

regex

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);
like image 500
MicMit Avatar asked Sep 20 '25 08:09

MicMit


2 Answers

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.

like image 134
blhsing Avatar answered Sep 22 '25 08:09

blhsing


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

like image 45
Ted Lyngmo Avatar answered Sep 22 '25 06:09

Ted Lyngmo