简体   繁体   English

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

[英]Escape parts of string with a character in c# using regex

I have a string such as this: 我有一个这样的字符串:

/one/two/three-four/five six seven/eight/nine ten eleven-twelve

I need to first replace dashes with spaces, and then be able to escape any grouping of words that have a space between them with a "#" symbol, so the above string should be: 我需要先将破折号替换为空格,然后才能使用“#”符号对在其之间具有空格的单词进行转义,因此上述字符串应为:

/one/two/#three four#/#five six seven#/eight/#nine ten eleven twelve#

I have the following extension method which works great for two words, but how can I make it work for any number of words. 我有以下扩展方法,适用于两个单词,但是如何使它适用于任意数量的单词。

 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);
    }

So I guess I really need help with the proper regex that takes into account that 所以我想我确实需要适当的正则表达式方面的帮助,并考虑到

  1. there could be any number of spaces 可以有任意数量的空格
  2. there may or may not be a trailing slash ("/") 斜线(“ /”)可能存在也可能没有
  3. takes into account that words are grouped between slashes, with the exception of #2 above. 考虑到单词在斜杠之间分组,上面的#2除外。
  4. Dashes are illegal and need to replaced with spaces 短划线是非法的,需要替换为空格

Thank you in advance for your support. 预先感谢您对我们的支持。

This should work for you: 这应该为您工作:

public static string QueryEscape(this string str)
{
    return Regex.Replace(str.Replace("-", " "), @"[^/]*(\s[^/]*)+", "#$&#");
}

Basically the idea is to match spans of text that isn't a slash that contains a (white-)space character in it. 基本上,该想法是匹配不是在其中包含(空格)字符的斜杠的文本范围。 Then add the pound signs around the match. 然后在比赛周围添加井号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM