-2

I have a value like this ab48/2012. How to extract the numbers from this string? I need to store 48 in one variable and 2012 in another variable.

Is it possible to extract numbers without using the substring function? If it is possible, please help me.

I have tried like this

string Value = "ab48/2012";
string[] array = value.Split('/');
int Value1 = Convert.ToInt32(array[0].Substring(2));
int Value2 = Convert.ToInt32(array[1].ToString());
4

8 回答 8

2

How about this?

int[] numbers = Regex.Split(Value, @"\D+")
                .Where(x => x.Length > 0)
                .Select(int.Parse)
                .ToArray();

NOTE: This does NOT handle negative numbers or numbers with decimal places.

于 2013-07-02T09:03:59.513 回答
1
string[] parts = "abc48/2012".Split('/');
int value1 = Int32.Parse(new String(parts[0].Where(Char.IsDigit).ToArray()));
int value2 = Int32.Parse(parts[1]);

If you find yourself using this sort of code a lot you could introduce a utility extension method e.g.

public static string GetIntegersOnly(this string str)
{
    return new String(str.Where(Char.IsDigit).ToArray());
}
...
int value1 = Int32.Parse(parts[0].GetIntegersOnly())
于 2013-07-02T09:00:40.643 回答
1
var input = "ab48/2012";
var regex = new Regex(@"^[^\d]*(?<a>\d*?)/(?<b>\d*)$");
var m = regex.Match(input);
if(m.Success)
{
    var a = m.Groups["a"].Value;
    var b = m.Groups["b"].Value;
    var aVal = int.Parse(a);
    var bVal = int.Parse(b);
}
于 2013-07-02T09:03:05.410 回答
0

You can use Regular Expression

var result = System.Text.RegularExpressions.Regex.Matches("abc48/2012", "[0-9]+", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            foreach(var val in result){
                var temp_variable = val;
            }
于 2013-07-02T09:01:27.610 回答
0

Perhaps:

string[] tokens = "ab48/2012".Split('/');
int num = int.Parse(new string(tokens.First().Where(Char.IsDigit).ToArray()));
int year = int.Parse(tokens.Last());

Demo

But in general i don't understand your reservations against Substring which is very efficient.

于 2013-07-02T09:02:05.977 回答
0

You can do like:

string value = "ab48/2012";
var charArray = value.ToCharArray().
           Reverse().TakeWhile(c=>char.IsDigit(c)).Reverse().ToArray();
var resultString = new string(charArray);
  • create char array
  • reverse it
  • get all chars till first NOT digit
  • reverse back
  • pass to char array
  • create a new string from that array
于 2013-07-02T09:02:58.870 回答
0

Try below code

var str = "ab48/2012";
            var strArr = string.Join("", str.Skip(2)).Split('/');
            Console.WriteLine(strArr[0]);
            Console.WriteLine(strArr[1]);
于 2013-07-02T09:04:23.807 回答
0

How about some Regex fu?

int value1, value2;
var match = Regex.Match(value, @"^[^\d]*(?<value1>[\d]+)/(?<value2>[\d]+)");
if (match.Success)
{
    value1 = int.Parse(match.Groups["value1"].Value);
    value2 = int.Parse(match.Groups["value2"].Value);
}
于 2013-07-02T09:05:28.537 回答