我遇到了一个我不太明白的困境。我正在计算许多包含单词之间大量空格的大文本字符串。我已经计算出要正确显示的文本,我需要用不间断的空格字符替换每个段中大约一半的空格。如果空格数为偶数或奇数,则情况会有所不同。我有个替代办法可以归结为:
if (numberOfSpaces > 3) {
double mathresult = (numberOfSpaces / 2);
int numberNBSP = Math.Ceiling(mathresult);
int numberSpace = Math.Floor(mathresult);
string replaceText;
for(numberNBSP > 0, numberNBSP--)
replaceText+=" ";
for(numberSpace > 0, numberSpace--)
replaceText+=" ";我现在的问题是为空间段的每个实例调用这个代码。每个片段都需要单独进行评估,我觉得我在RegEx中有一个盲点,就是如何这样做。我希望这是有意义的,谢谢您抽出时间阅读!
发布于 2022-01-03 15:31:56
这只是一个将回调传递给Replace的问题,它将对所做的每一次匹配执行。
例如:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string input = "I hope this makes sense, thank you for taking the time to read this!";
Console.WriteLine("input: " + input);
Regex rx = new Regex(@" +");
string output = rx.Replace(input, Evaluator);
Console.WriteLine("output: " + output);
}
static string Evaluator(Match match)
{
string replaceText;
int numberOfSpaces = match.Value.Length;
if (numberOfSpaces > 3) {
double mathresult = (numberOfSpaces / 2);
int numberNBSP = (int) Math.Ceiling(mathresult);
int numberSpace = (int) Math.Floor(mathresult);
replaceText = "";
for (; numberNBSP > 0; numberNBSP--) replaceText += " ";
for (; numberSpace > 0; numberSpace--) replaceText += " ";
} else {
replaceText = match.Value;
}
return replaceText;
}
}显然,替换空格的逻辑是你自己的,我没有研究过。
或者,您可以使用与4个或更多空格字符匹配的regex字符串" {4,}",然后可以去掉if (numberOfSpaces > 3)测试等。
如果您希望能够匹配所有空白,例如制表符和换行符,那么使用\s而不是单个空格字符。
https://stackoverflow.com/questions/70567482
复制相似问题