user3726891
user3726891

Reputation: 11

How to split number with their signs from text

I'm trying to split numbers with signs from a text. I'm use Regex. For example i have this equation:

12X-3Y<=-6

In the code below, you can see what I've done:

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

but this code only split numbers from the other characters. i.e:

12 3 6

I want these number with signs.

12 -3 -6

Upvotes: 1

Views: 111

Answers (3)

Nicholas Carey
Nicholas Carey

Reputation: 74227

You might try something like this:

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

which yields

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

Easy!

The regular expression should match any base-10 literal. It can be broken down as follows:

-?              # 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
)?              #

Upvotes: 1

TheBlindSpring
TheBlindSpring

Reputation: 631

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

Not the prettiest but it should work.

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

I think you're pretty close, just use \d instead of \D, capture the -, and use Regex.Match instead of split:

(-?\d+)

Regular expression visualization

Usage

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

    }
}

You could string those Captures together like this:

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

Debuggex Demo

Upvotes: 1

Related Questions