locked
Regular expression to allow negative and positive numbers? RRS feed

  • Question

  • Say I have a string that looks like As3H22Br-84Si335Nm+21

    The following code will separate the numbers and letters from the string and spit them into 2 separate string arrays.

    var numRegx = new Regex(@"\d+");
    
                var numbers = numRegx.Matches(input).Cast<Match>().Select(m => m.Value).ToArray();
    
                var wordRegx = new Regex(@"[a-zA-Z]+");
                var words = wordRegx.Matches(input).Cast<Match>().Select(m => m.Value).ToArray();

    Right now, it's only accepting just positive numbers. How do I modify the regex(@"\d+") also check for negative numbers?
    Wednesday, October 2, 2013 8:35 AM

Answers

  • But it did.  My app is working perfectly with \-*\d+ while it throws an error  with -?\d|[a-zA-Z].  Don't ask me how or why. 

    • Marked as answer by Anne Jing Wednesday, October 9, 2013 1:22 AM
    Wednesday, October 2, 2013 4:36 PM

All replies

  • Hello ChemCat,

    Try this:

    -?\d|[a-zA-Z]
    • Marked as answer by RandyPete Wednesday, October 2, 2013 9:28 AM
    • Unmarked as answer by RandyPete Wednesday, October 2, 2013 9:28 AM
    Wednesday, October 2, 2013 8:52 AM
  • Actually, that doesn't work.  However, after playing around a bit, I found the answer.

    \-*\d+

    Now I'm embarrassed.  It's so simple.

    Wednesday, October 2, 2013 9:29 AM
  • Hello ChemCat,

    But it can't take like that input: As3H22Br-84Si335Nm-21

    Wednesday, October 2, 2013 10:18 AM
  • But it did.  My app is working perfectly with \-*\d+ while it throws an error  with -?\d|[a-zA-Z].  Don't ask me how or why. 

    • Marked as answer by Anne Jing Wednesday, October 9, 2013 1:22 AM
    Wednesday, October 2, 2013 4:36 PM