正则表达式查找字符串中的重复模式

Regex to find a repeating pattern in a string

这是我正在使用的示例字符串:
- - - some text followed by more - - followed by more - -
我需要在行首找到每个出现的 - 并替换为另一个字符。所以,如果一个-要被~代替,最后的结果就是
~ ~ ~ some text followed by more - - followed by more - -

我试过 (-).?,它选择了所有 -。如果我用 ^ 表示行首,我只会得到第一个“-”。如果我将模式指定为 ^((-)\s){3},它会选择组,但是组在开始时可以是任意数量的 -,因此
- - some text is valid
- some text is valid
- - - - some text is valid

有几种方法:从上一个匹配项 (\G) 的开头或结尾匹配除 - ([^\w-]*) 以外的任何 0+ 非单词字符并捕获它们(使用 (...)),然后匹配 - 并用替换字符(~)替换为对第一个捕获组(</code>)的反向引用:</p> <pre><code>var res = Regex.Replace(s, @"\G([^\w-]*)-", "~");

参见regex demo

或者,匹配字符串 (^) 开头的所有 1 个或多个非单词字符 (\W+),并将 - 替换为 ~只有那里:

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

参见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 - - 

或者,您可以利用可变宽度后视:

(?<=^\W*)-

替换为~。参见 this regex demo(?<=^\W*) lookbehind 只会匹配 - 如果它前面有 0+ 个非单词字符从字符串的开头。