C#删除空的url参数正则表达式 [英] C# remove empty url parameters regex

查看:50
本文介绍了C#删除空的url参数正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 C# 从字符串中删除空的 url 类型参数.我的代码示例在这里.

I am trying to remove empty url type parameters from a string using C#. My code sample is here.

    public static string test ()
    {
        string parameters = "one=aa&two=&three=aaa&four=";
        string pattern = "&[a-zA-Z][a-zA-Z]*=&";
        string replacement = "";
        Regex rgx = new Regex(pattern);
        string result = rgx.Replace(parameters, replacement);

        return parameters;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(test());
    }

我在 rextester

输出:one=aa&two=&three=aaa&four=

预期输出:one=aa&three=aaa

推荐答案

Regex:

(?:^|&)[a-zA-Z]+=(?=&|$)

这匹配字符串的开头或与号 ((?:^|&)) 后跟至少一个(英文)字母 ([a-zA-Z]+),一个等号 (=),然后什么都没有,通过与 end 匹配的正向预测 ((?=&|$))字符串或新参数(以 & 开头).

This matches start of string or an ampersand ((?:^|&)) followed by at least one (english) letter ([a-zA-Z]+), an equal sign (=) and then nothing, made sure by the positive look-ahead ((?=&|$)) which matches end of string or a new parameter (started by &).

代码:

public static string test ()
{
    string parameters = "one=aa&two=&three=aaa&four=";
    string pattern = "(?:^|&)[a-zA-Z]+=(?=&|$)";
    string replacement = "";
    Regex rgx = new Regex(pattern);
    string result = rgx.Replace(parameters, replacement);

    return result;
}

public static void Main(string[] args)
{
    Console.WriteLine(test());
}

请注意,这也会返回正确的变量(如 Joel Anderson 所指出的)

Note that this also returns the correct variable (as pointed out by Joel Anderson)

在 ideone 现场直播.

这篇关于C#删除空的url参数正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆