-4

I need to extract a substring from an existing string. This String starts with uninteresting characters (include "," "space" and numbers) and ends with ", 123," or ", 57," or something like this where the numbers can change. I only need the Numbers. Thanks

Pascal
  • 23
  • 3
  • 2
    Have you tried anything so far? – Jerry May 29 '13 at 13:03
  • Can you please give an example of input and desired output? – alex.b May 29 '13 at 13:03
  • What is `uninteresting character`? – Soner Gönül May 29 '13 at 13:05
  • 2
    Where there are a few questions I have. Like Jerry Said what have you tried, also you included comma's inside the quotes, is that an always expected pattern, if so are your numbers always last after the last comma? If they are then just split by comma and take the last indice in the array. If this is not a typical then with out knowing a few more specifics about the expected format of the string I dont think there is much that can be done here minus the regex expressions. – Bearcat9425 May 29 '13 at 13:10

5 Answers5

1

Regex to match numbers: Regex regex = new Regex(@"\d+");

Source (slightly modified): Regex for numbers only

Community
  • 1
  • 1
tnw
  • 13,521
  • 15
  • 70
  • 111
1
public static void Main(string[] args)
{
    string input = "This is 2 much junk, 123,";
    var match = Regex.Match(input, @"(\d*),$");  // Ends with at least one digit 
                                                 // followed by comma, 
                                                 // grab the digits.
    if(match.Success)
        Console.WriteLine(match.Groups[1]);  // Prints '123'
}
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

I think this is what you're looking for:

Remove all non numeric characters from a string using Regex

using System.Text.RegularExpressions;
...
string newString = Regex.Replace(oldString, "[^.0-9]", "");

(If you don't want to allow the decimal delimiter in the final result, remove the . from the regular expression above).

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
Annish
  • 2,145
  • 1
  • 14
  • 15
  • While the link provided could offer or not the right answer, placing a link only answer is not considered a good answer, please elaborate. – Steve May 29 '13 at 13:08
0

You can use \d+ to match all digits within a given string

So your code would be

var lst=Regex.Matches(inp,reg)
             .Cast<Match>()
             .Select(x=x.Value);

lst now contain all the numbers


But if your input would be same as provided in your question you don't need regex

input.Substring(input.LastIndexOf(", "),input.LastIndexOf(","));
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

Try something like this :

String numbers =  new String(yourString.TakeWhile(x => char.IsNumber(x)).ToArray());      
MHeads
  • 267
  • 1
  • 7
  • 18