【问题标题】:C# extract words using regexC# 使用正则表达式提取单词
【发布时间】:2011-04-05 15:58:40
【问题描述】:

我找到了很多关于如何使用正则表达式检查内容或如何使用正则表达式拆分文本的示例。

但是如何从字符串中提取单词呢?

例子:

aaaa 12312 <asdad> 12334 </asdad>

假设我有这样的东西,我想提取所有数字 [0-9]* 并将它们放在一个列表中。

或者如果我有 2 种不同的元素:

aaaa 1234 ...... 1234 ::::: asgsgd

我想choose digits that come after .....words that come after ::::::

我可以在一个正则表达式中提取这些字符串吗?

【问题讨论】:

    标签: c# regex parsing


    【解决方案1】:

    在一般情况下,您可以使用捕获括号来做到这一点:

    string input = "aaaa 1234 ...... 1234 ::::: asgsgd";
    string regex = @"\.\.\.\. (\d+) ::::: (\w+)";
    Match m = Regex.Match(input, regex);
    
    if (m.Success) {
        int numberAfterDots = int.Parse(m.Groups[1].Value);
        string wordAfterColons = m.Groups[2].Value;
        // ... Do something with these values
    }
    

    但是你问的第一部分(提取所有数字)要容易一些:

    string input = "aaaa 1234 ...... 1234 ::::: asgsgd";
    var numbers = Regex.Matches(input, @"\d+")
                       .Cast<Match>()
                       .Select(m => int.Parse(m.Value))
                       .ToList();
    

    现在numbers 将是一个整数列表。

    【讨论】:

    • 那么 () 中的每个表达式都会被分组?
    • 是的。请注意,组编号从 1 开始。另请参阅我对此答案的最新编辑。
    【解决方案2】:

    这是您第一个问题的解决方案:

       class Program
        {
            static void Main(string[] args)
            {
                string data = "aaaa 12312 <asdad> 12334 </asdad>";
    
                Regex reg = new Regex("[0-9]+");
    
                foreach (var match in reg.Matches(data))
                {
                    Console.WriteLine(match);
                }
    
                Console.ReadLine();
            }
        }
    

    【讨论】:

      【解决方案3】:

      对于您的具体示例:

          string firstString = "aaaa 12312 <asdad> 12334 </asdad>";
          Regex firstRegex = new Regex(@"(?<Digits>[\d]+)", RegexOptions.ExplicitCapture);
          if (firstRegex.IsMatch(firstString))
          {
              MatchCollection firstMatches = firstRegex.Matches(firstString);
              foreach (Match match in firstMatches)
              {
                  Console.WriteLine("Digits: " + match.Groups["Digits"].Value);
              }
          }
      
          string secondString = "aaaa 1234 ...... 1234 ::::: asgsgd";
          Regex secondRegex = new Regex(@"([\.]+\s(?<Digits>[\d]+))|([\:]+\s(?<Words>[a-zA-Z]+))", RegexOptions.ExplicitCapture);
          if (secondRegex.IsMatch(secondString))
          {
              MatchCollection secondMatches = secondRegex.Matches(secondString);
              foreach (Match match in secondMatches)
              {
                  if (match.Groups["Digits"].Success)
                  {
                      Console.WriteLine("Digits: " + match.Groups["Digits"].Value);
                  }
                  if (match.Groups["Words"].Success)
                  {
                      Console.WriteLine("Words: " + match.Groups["Words"].Value);
                  }
              }
          }
      

      希望对您有所帮助。输出是:

      Digits: 12312
      Digits: 12334
      Digits: 1234
      Words: asgsgd
      

      【讨论】:

      • 显式捕获不是必需的,但是它们可以让您重新排列括号组并且您不必更改代码,因为您使用 NAMES 组而不是顺序定位。这就是为什么我在匹配组中使用“数字”和“单词”而不是 \1 和 \2。显式捕获组的命名是通过在“(”内添加“?”来完成的,当然所有都没有引号。
      【解决方案4】:

      这样的事情会做得很好!

      var text = "aaaa 12312 <asdad> 12334 </asdad>";
      var matches = Regex.Matches(text, @"\w+");
      
      var arrayOfMatched = matches.Cast<Match>().Select(m => m.Value).ToArray();
      
      Console.WriteLine(string.Join(", ", arrayOfMatched));
      

      \w+ 匹配连续的单词字符。然后我们只是从匹配列表中选择值并将它们变成一个数组。

      【讨论】:

        【解决方案5】:
        Regex itemsRegex = new Regex(@"(\d*)");
        MatchCollection matches = itemsRegex.Matches(text);
        
        int[] values = matches.Cast<Match>().Select(m => Convert.ToInt32(m.Value)).ToArray();
        

        【讨论】:

          【解决方案6】:
              Regex phoneregex = new Regex("[0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9]");
              String unicornCanneryDirectory = "unicorn cannery 483-8627 cha..."
              String numbersToCall = "";
          
              //the second argument is where to begin within the match, 
              //we probably want 0, the first character
              Match matchIterator = phoneregex.Match(unicornCanneryDirectory , 0);
              //Success tells us if matchIterator has another match or not
              while( matchIterator.Sucess){
                String aResult = matchIterator.Result();
                //we could manipulate our match now but I'm going to concatenate them all for later
                numbersToCall  += aResult + " ";
          
                matchIterator = matchIterator.NextMatch();
              }
          
              // use my concatenated matches now
              String message = "Unicorn rights activists demand more sparkles in the unicorn canneries under the new law...";
              phoneDialer.MassCallWithAutomatedMessage(aResult, message );
          

          http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.nextmatch.aspx

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-31
            • 2011-12-31
            • 1970-01-01
            • 2021-10-30
            • 2021-12-24
            相关资源
            最近更新 更多