1

是否可以从整个字符串中删除每个出现的字符 + 一个字符?

这是一个实现我描述的代码,但相当大:

private static string FilterText(string text){
string filteredText = text;

while (true)
{
    int comaIndex = filteredText.IndexOf('.');

    if (comaIndex == -1)
    {
        break;
    }
    else if (comaIndex > 1)
    {
        filteredText = filteredText.Substring(0, comaIndex) + filteredText.Substring(comaIndex + 2);
    }
    else if (comaIndex == 1)
    {
        filteredText = filteredText[0] + filteredText.Substring(comaIndex + 2);
    }
    else
    {
        filteredText = filteredText.Substring(comaIndex + 2);
    }
}

return filteredText;
}

此代码将例如输入.Otest.1 .2.,string.w..test string

使用正则表达式是否可以达到相同的结果?

4

2 回答 2

2

你想用

var output = Regex.Replace(text, @"\..", RegexOptions.Singleline);

请参阅.NET 正则表达式演示详情

  • \.- 匹配一个点
  • .RegexOptions.Singleline- 由于使用的选项,匹配任何字符,包括换行字符。
于 2021-08-04T20:57:42.493 回答
0

试试这个模式:(?<!\.)\w+

代码:

using System;
using System.Text.RegularExpressions;

public class Test{
    public static void Main(){
        string str = ".Otest.1 .2.,string.w..";
        Console.WriteLine(FilterText(str));

    }
    private static string FilterText(string text){
        string pattern = @"(?<!\.)\w+";  
        string result = "";
        foreach(Match m in Regex.Matches(text, pattern)){
            result += m + " ";
        }
        return result;
    }
}

输出:

test string 
于 2021-08-04T18:58:49.527 回答