首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态评估Regex匹配

动态评估Regex匹配
EN

Stack Overflow用户
提问于 2022-01-03 14:47:50
回答 1查看 38关注 0票数 0

我遇到了一个我不太明白的困境。我正在计算许多包含单词之间大量空格的大文本字符串。我已经计算出要正确显示的文本,我需要用不间断的空格字符替换每个段中大约一半的空格。如果空格数为偶数或奇数,则情况会有所不同。我有个替代办法可以归结为:

代码语言:javascript
复制
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中有一个盲点,就是如何这样做。我希望这是有意义的,谢谢您抽出时间阅读!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-03 15:31:56

这只是一个将回调传递给Replace的问题,它将对所做的每一次匹配执行。

例如:

代码语言:javascript
复制
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而不是单个空格字符。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70567482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档