【问题标题】:Regex to strip characters except given ones?正则表达式去除给定字符以外的字符?
【发布时间】:2012-06-11 22:00:28
【问题描述】:

我想删除字符串,但只留下以下内容:

[a-zA-Z]+[_a-zA-Z0-9-]*

我正在尝试输出以字符开头的字符串,然后可以包含字母数字、下划线和破折号。如何使用 RegEx 或其他函数做到这一点?

【问题讨论】:

  • 你有正则表达式 - 你到底有什么问题?
  • 你所说的字符串是指string[]? “得到所有匹配”与“不得到不匹配的东西”不是一样的吗?

标签: c# .net regex string c#-4.0


【解决方案1】:

因为正则表达式第二部分中的所有内容都在第一部分中,所以您可以执行以下操作:

String foo = "_-abc.!@#$5o993idl;)"; // your string here.
//First replace removes all the characters you don't want.
foo = Regex.Replace(foo, "[^_a-zA-Z0-9-]", "");
//Second replace removes any characters from the start that aren't allowed there.
foo = Regex.Replace(foo, "^[^a-zA-Z]+", "");

因此,首先将其缩减为仅允许的字符。然后去掉所有不能在开头的允许字符。

当然,如果你的正则表达式变得更复杂,这个解决方案很快就会崩溃。

【讨论】:

    【解决方案2】:

    假设你在一个集合中有字符串,我会这样做:

    1. 集合中的foreach元素尝试匹配正则表达式
    2. 如果 !success,从集合中删除字符串

    或者反过来 - 如果匹配,将其添加到新集合中。

    如果字符串不在集合中,您能否添加更多关于您的输入内容的详细信息?

    【讨论】:

      【解决方案3】:

      如果你想提取所有匹配你的正则表达式的标识符,你可以这样做:

      var input = " _wontmatch f_oobar0 another_valid ";
      var re = new Regex( @"\b[a-zA-Z][_a-zA-Z0-9-]*\b" );
      foreach( Match match in re.Matches( input ) )
          Console.WriteLine( match.Value );
      

      【讨论】:

        【解决方案4】:

        使用MatchCollection matchColl = Regex.Matches("input string","your regex");

        然后使用:

        string [] outStrings = new string[matchColl.Count]; //A string array to contain all required strings
        
        for (int i=0; i < matchColl.Count; i++ )
             outStrings[i] = matchColl[i].ToString();
        

        您将在 outStrings 中拥有所有必需的字符串。希望这会有所帮助。

        【讨论】:

          【解决方案5】:

          编辑

             var s = Regex.Matches(input_string, "[a-z]+(_*-*[a-z0-9]*)*", RegexOptions.IgnoreCase);
                      string output_string="";
                      foreach (Match m in s)
                      {
                          output_string = output_string + m;
          
                      }
              MessageBox.Show(output_string);
          

          【讨论】:

          • 这很奇怪.. 输入这个 sdgfsd*^%&$AFSds 返回 sdgfsd。好像找到一个特殊的字符串就退出了。
          • @TruMan1 你说的脱衣舞是什么意思? OP 正在询问从给定字符串中剥离字符串。
          • 我希望 sdgfsd*^%&$AFSds 返回 sdgfsdAFSds 但它正在返回 sdgfsd。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-02
          • 2015-04-24
          • 2015-10-07
          • 1970-01-01
          相关资源
          最近更新 更多