You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何从给定字符串中移除URL并实现无URL时提示功能

问题分析

原代码存在3类问题导致无法正常运行:

  • 语法错误:string.Substring方法参数不符合要求,该方法接收数值类型的起始索引、截取长度作为入参,不支持传入起止字符串做截取;方法缺少返回值,逻辑执行完成后没有返回处理结果
  • 逻辑漏洞:仅靠空格判断URL结束位置,无法处理URL在字符串末尾、后方无空格的场景;未做无URL场景的判断,无法输出指定提示
  • 覆盖不全:仅识别https://开头的链接,未覆盖http://的常见URL场景
修复后完整代码
using System;
using System.Text.RegularExpressions;

namespace UrlsDetector
{
    class UrlDetector
    {
        public static string RemoveUrl(string input)
        {
            // 匹配http/https开头URL的正则规则
            string urlMatchRule = @"https?://\S+";
            // 无匹配URL时直接返回提示
            if (!Regex.IsMatch(input, urlMatchRule))
            {
                return "the sentence you input doesn't have url";
            }
            // 替换所有URL,清理末尾残留空格
            string processed = Regex.Replace(input, urlMatchRule, string.Empty).TrimEnd();
            return processed;
        }
    }

    class Program
    {
        static void Main()
        {
            // 测试带URL场景
            Console.WriteLine(UrlDetector.RemoveUrl("I saw a cat and a horse on https://www.youtube.com/"));
            // 测试无URL场景
            Console.WriteLine(UrlDetector.RemoveUrl("I saw a cat and a horse on the grassland"));
        }
    }
}
实现说明
  • 正则规则https?://\S+中,s?兼容http、https两种协议,\S+匹配协议后所有连续非空白字符,无论URL在句子中间还是末尾、带路径/参数都能完整匹配
  • 替换URL后调用TrimEnd()清除末尾多余空格,避免输出内容尾部残留无意义空白
  • 支持一次性替换句子中出现的多个URL,无需循环逐次处理
运行结果
  • 输入带URL的测试句:输出I saw a cat and a horse on,符合预期
  • 输入无URL的句子:输出the sentence you input doesn't have url,符合预期

内容的提问来源于stack exchange,提问作者James Exe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 02:51:26