Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用正则表达式用c#中的字符转义字符串部分_C#_Regex_String_Escaping - Fatal编程技术网

使用正则表达式用c#中的字符转义字符串部分

使用正则表达式用c#中的字符转义字符串部分,c#,regex,string,escaping,C#,Regex,String,Escaping,我有这样一个字符串: /one/two/three-four/five six seven/eight/nine ten eleven-twelve 我需要首先将破折号替换为空格,然后能够用“#”符号转义任何一组单词,因此上面的字符串应该是: /one/two/#three four#/#five six seven#/eight/#nine ten eleven twelve# 我有下面的扩展方法,它对两个单词非常有效,但是如何使它对任意数量的单词都有效呢 public static s

我有这样一个字符串:

/one/two/three-four/five six seven/eight/nine ten eleven-twelve
我需要首先将破折号替换为空格,然后能够用“#”符号转义任何一组单词,因此上面的字符串应该是:

/one/two/#three four#/#five six seven#/eight/#nine ten eleven twelve#
我有下面的扩展方法,它对两个单词非常有效,但是如何使它对任意数量的单词都有效呢

 public static string QueryEscape(this string str)
    {
        str = str.Replace("-", " ");
        return Regex.Replace(str, @"(\w*) (\w*)", new MatchEvaluator(EscapeMatch));
    }

private static string EscapeMatch(Match match)
    {
        return string.Format("#{0}#", match.Value);
    }
所以我想我真的需要帮助使用适当的正则表达式来考虑这一点

  • 可以有任意数量的空格
  • 后面可能有也可能没有斜杠(“/”)
  • 考虑到除上面的#2之外,单词在斜杠之间分组
  • 破折号是非法的,需要用空格替换

  • 提前感谢您的支持。

    这应该适合您:

    public static string QueryEscape(this string str)
    {
        return Regex.Replace(str.Replace("-", " "), @"[^/]*(\s[^/]*)+", "#$&#");
    }
    
    基本上,这个想法是匹配文本的跨度,而不是包含(白色)空格字符的斜杠。然后在比赛周围加上英镑符号