Regex to find a repeating pattern in a string

Viewed 3076

Here is a sample string that I am working with:
- - - some text followed by more - - followed by more - -
I need to find each occurrence of a - at the beginning of the line and replace with another character. So, if a - is to be replaced by ~, the final outcome will be
~ ~ ~ some text followed by more - - followed by more - -

I have tried (-).?, which selects all the -. If I put a ^ to indicate beginning of line, I get just the 1st '-'. If I give the pattern as ^((-)\s){3}, which selects the group, but then the group could be any number of - in the beginning, so
- - some text is valid and
- some text is valid and
- - - - some text is valid

1 Answers

There are several ways: match any 0+ non-word chars other than - ([^\w-]*) from the start or from the end of the previous match (\G) and capture them (with (...)), then match - and replace with a backreference to the first capturing group ($1) with a replacement char (~):

var res = Regex.Replace(s, @"\G([^\w-]*)-", "$1~");

See the regex demo.

Or, match all 1 or more non-word chars (\W+) at the start of the string (^) and replace the - with ~ only there:

var res = Regex.Replace(s, @"^\W+", m => m.Value.Replace("-","~"));

See the C# demo:

var s = "- - - some text followed by more - - followed by more - - ";
var res = Regex.Replace(s, @"^\W+", m => m.Value.Replace("-", "~"));
Console.WriteLine(res); 
// => ~ ~ ~ some text followed by more - - followed by more - - 

Alternatively, you may leverage the variable width lookbehind:

(?<=^\W*)-

Replace with ~. See this regex demo. The (?<=^\W*) lookbehind will only make the - match if it is preceded with 0+ non-word chars from the start of the string.

Related