-1

这是我在form1按钮事件中的代码:

StringBuilder sb = new StringBuilder();
var words = Regex.Split(textBox1.Text, @"(?=(?<=[^\s])\s+)");
foreach (string word in words)
{
    ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(word.Trim());
    scrmbltb.GetText();
    sb.Append(word.Replace(word.Trim(), scrmbltb.scrambledWord));
}
textBox2.AppendText(sb.ToString());

我得到了我想要的所有单词,textBox1但有些单词也是----?/或之类的符号\n\r

我只想解析/获取用字母构建的单词。

我该如何过滤它?

我试着这样做:

StringBuilder sb = new StringBuilder();
            var words = Regex.Split(textBox1.Text, @"(?=(?<=[^\s])\s+\\w+)".Cast<Match>().Select(match => match.Value));
            var matches = Regex.Matches(textBox1.Text, "\\w+").Cast<Match>().Select(match => match.Value);
            foreach (string word in words)
            {
                ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(word.Trim());
                scrmbltb.GetText();
                sb.Append(word.Replace(word.Trim(), scrmbltb.scrambledWord));
            }
            textBox2.AppendText(sb.ToString());

我需要 var 单词,因为 Regex.Split 对我很有效,可以复制 textBox1 和 textBox2 之间的空格。所以我尝试添加 "\w+" 和 .Cast().Select(match => match.Value 所以它将在变量词中一起出现,但我现在在 var 词上出现错误:

错误 1 ​​'System.Text.RegularExpressions.Regex.Split(string, int)' 的最佳重载方法匹配有一些无效参数

错误 2 参数 2:无法从 'System.Collections.Generic.IEnumerable' 转换为 'int'

我该如何解决?

我现在试过了,但没有用:

var words = Regex.Matches(textBox1.Text, @"(?=(?<=[^\s])\s+\\w+)").Cast<Match>().Select(match => match.Value);

我现在什么话都说不出来。

4

2 回答 2

1

试试这个:

var matches = Regex.Matches(textBox1.Text, "\\w+").Cast<Match>().Select(match => match.Value);

应该给你所有没有空字符串的单词。

整个代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {

      var matches = Regex.Matches("Line 1 this is any random text. \r\n Line 2 Another Line?! \r\n Line 3 End of text. ", "\\w+").Cast<Match>().Select(match => match.Value);
      foreach (string sWord in matches)
      {
        Console.WriteLine(sWord);
      }

    }
  }
}
于 2013-07-03T13:19:25.813 回答
0

如果你想用正则表达式来做,特别是只想要字母,你可以这样做(匹配而不是拆分):

var words = Regex.Matches(Test, @"[a-zA-Z]+");"

相反,您可能想要"[\w]+",因为我怀疑您所追求的某些字符/数字会出现。

于 2013-07-03T13:11:10.037 回答