If you are on .NET3.5+ you can use LINQ
. A solution without Regex (which is faster) is the following:
var strings = new List<string>() { "82&?", "82,9", "abse82,9>dpkg" };
var result = strings.Select(s =>
String.Join("",
s.Where(c => char.IsNumber(c) || c == ',')
.ToArray()) /* .ToArray() is not needed on .NET 4 */
).ToList();
It only select characters that are numbers or comma. But given the string 8,1aa1
it would return 8,11
.
This other method is a bit slower, but it will take 8,1
from 8,1aa1
and will not take 8,a
or a,a
:
var strings = new List<string>() { "82&?887..2", "82,9", "abse82,9>dpkg" };
var result = strings.Select(s =>
String.Join("",
s.SkipWhile(c => !char.IsNumber(c))
.TakeWhile(c => (char.IsNumber(c) || c == ','))
.ToArray()
)
).Where(s => char.IsNumber(s.LastOrDefault())).ToList();
Running a test (using Stopwatch) with 100,000 iterations with the methods presented on the answers I got:
Fn: BrunoLM (Method 1)
Ticks: 524999
Fn: BrunoLM (Method 2)
Ticks: 729460
Fn: Ahmad
Ticks: 1323366
Fn: Josh
Ticks: 3783158
The same test with 1000~ length string:
var strings = new List<string>() { "82&?887..2".PadRight(1000, '2'), "82,9".PadRight(1000, '1'), "abse82,9>dpkg".PadRight(1000, 'f') };
Result:
Fn: Ahmad
Ticks: 11911332
Fn: BrunoLM (Method 2)
Ticks: 28149495
Fn: Josh
Ticks: 213681541
Further reading:
regular expression and text size n