如何用文字中的符号分割数字

时间:2014-06-10 16:39:45

标签: c# regex

我正在尝试用文字中的符号分割数字。我正在使用正则表达式。例如,我有这个等式:

  

12X-3Y< = - 6

在下面的代码中,您可以看到我做了什么:

string[] numOfConstraint = Regex.Split(richTextBox2.Text, @"\D+");

但此代码仅拆分其他字符中的数字。即:

  

12 3 6

我希望这些号码带有标志。

  

12 -3 -6

3 个答案:

答案 0 :(得分:1)

我认为您非常接近,只需使用\d代替\D,捕获-,然后使用Regex.Match代替分割:

(-?\d+)

Regular expression visualization

用法

var match = Regex.Match(pattern, input);
if (match.Success)
{
    foreach (var g in match.Captures)
    {

    }
}

你可以像这样将Captures串起来:

var s = string.Join(" ", match.Captures
    .Select(c => c.Value)
    .ToArray());

Debuggex Demo

答案 1 :(得分:1)

您可以尝试这样的事情:

string text = @"12x-3y<=-6" ;
Regex rx = new Regex( @"-?\d+(\.\d+)?([Ee][+-]?\d+)?") ;
string[] words = rx
                 .Matches(text)
                 .Cast<Match>()
                 .Select( m => m.Value )
                 .ToArray()
                 ;

产生

words[0] = "12
words[2] = "-3"
words[4] = "-6"

容易!

正则表达式应匹配任何base-10文字。它可以分解如下:

-?              # an optional minus sign, followed by
\d+             # 1 or more decimal digits, followed by
(               # an optional fractional component, consisting of
  \.            # - a decimal point, followed by
  \d+           # - 1 or more decimal digits.
)?              # followed by
(               # an optional exponent, consisting of
  [Ee]          # - the letter "E" , followed by
  [+-]?         # - an optional positive or negative sign, followed by
  \d+           # - 1 or more decimal digits
)?              #

答案 2 :(得分:0)

List<string> strList = new List<string>();
List<float> fltList = new List<float>();
 StringBuilder sb = new StringBuilder();
 for(int i = 0; i < richTextBox.Text.Length; i++)
 {
  if(!char.IsDigit(richTextBox.Text[i]) && richTextBox.Text[i] != "-")
       {
        if(sb.ToString().Length > 0)
            strList.Add(sb.ToString());

        sb.Clear();
       }
   else
       sb.Add(richTextBox.Text[i]);
   }

  float numOut;
  foreach(string num in strList)
  {
    if( float.TryParse(num, out numOut) )
        fltList.Add(numOut);
  }

不是最漂亮但应该有用。