开发者

C# Regular Expression to return only the numbers

Let's say I have the followi开发者_Python百科ng within my source code, and I want to return only the numbers within the string:

The source is coming from a website, just fyi, and I already have it parsed out so that it comes into the program, but then I need to actually parse these numbers to return what I want. Just having a doosy of a time trying to figure it out tho :(

like: 13|100|0;

How could I write this regex?

    var cData = new Array(
        "g;13|g;100|g;0", 
        "g;40|g;100|g;1.37", 
        "h;43|h;100|h;0", 
        "h;27|h;100|h;0", 
        "i;34|i;100|i;0", 
        "i;39|i;100|i;0", 
    );


Not sure you actually need regex here.

var str = "g;13|g;100|g;0";
str = str.Replace("g;", "");

would give you "13|100|0".

Or a slight improvement on spinon's answer:

// \- included in case numbers can be negative.  Leave it out if not.
Regex.Replace("g;13|g;100|g;0", "[^0-9\|\.\-]", "");  

Or an option using split and join:

String.Join("|", "g;13|g;100|g;0".Split('|').Select(pipe => pipe.Split(';')[1]));


I would use something like this so you only keep numbers and separator:

Regex.Replace("g;13|g;100|g;0", "[^0-9|]", "");


Regex might be overkill in this case. Given the uniform delimiting of | and ; I would recommend String.Split(). Then you could either split again or use String.Replace() to get rid of the extra chars (i.e. g;).


It looks like you have a number of solutions, but I'll throw in one more where you can iterate over each group in a match to get the number out if you want.

Regex regexObj = new Regex(@"\w;([\d|.]+)\|?");
Match matchResults = regexObj.Match("g;13|g;100|g;0");
if( matchResults.IsMatch )
{
   for (int i = 1; i < matchResults.Groups.Count; i++) 
   {
      Group groupObj = matchResults.Groups[i];
      if (groupObj.Success) 
      {
         //groupObj.Value will be the number you want
      } 
   }
}

I hope this is helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜