Regex 使用Parallel.ForEach将每个字符替换为大写
我正在尝试将字符串中的每个字符替换为大写,以了解如何使用parallel.ForEach进行并行编程。总的tMatch计数约为136945 输出文件的顺序不正确。替换字符的位置不正确。我知道parallel.ForEach不是同步进程 请指导我需要做什么/知道什么才能获得预期的产出。我的代码是:Regex 使用Parallel.ForEach将每个字符替换为大写,regex,c#-4.0,parallel.foreach,Regex,C# 4.0,Parallel.foreach,我正在尝试将字符串中的每个字符替换为大写,以了解如何使用parallel.ForEach进行并行编程。总的tMatch计数约为136945 输出文件的顺序不正确。替换字符的位置不正确。我知道parallel.ForEach不是同步进程 请指导我需要做什么/知道什么才能获得预期的产出。我的代码是: MatchCollection tMatches = Regex.Matches(_testString, @".", RegexOptions.None); Parallel.ForEach(tMat
MatchCollection tMatches = Regex.Matches(_testString, @".", RegexOptions.None);
Parallel.ForEach(tMatches.OfType<Match>(), tMatch =>
{
_testString = _testString.Remove(tMatch.Index, tMatch.Value.Length);
_testString = _testString.Insert(tMatch.Index, tMatch.Value.ToUpper());
});
Input:
abcdefgh
Expected Output:
ABCDEFGH
MatchCollection tMatches=Regex.Matches(_testString,@“.”,RegexOptions.None);
Parallel.ForEach(tMatches.OfType(),tMatch=>
{
_testString=_testString.Remove(tMatch.Index、tMatch.Value.Length);
_testString=_testString.Insert(tMatch.Index,tMatch.Value.ToUpper());
});
输入:
abcdefgh
预期产出:
ABCDEFGH
您所做的实际上相当于Regex.Replace(_testString,@“.”,tMatch=>tMatch.Value.ToUpper())代码>。实际上,为什么不只匹配小写字母,而不匹配除换行符以外的任何字符?使用@“\p{Ll}”
regex.@WiktorStribiżew,所以在并行foreach中是不可能的?我的意思是,这是一个糟糕的用法示例。在这种情况下,您不应该使用它。