Stampy
Stampy

Reputation: 466

Replace all characters after the first number block

I have an array with strings like COM1, COM22, COM3abc, COM4!"§", COM5656! and so on. Now a want to replace all characters after the first block of numbers occurred so that I get: COM1, COM22, COM3, COM4, COM5656. I'm not so familiar with regex but I tried a lot of different regex like:

for (var i = 0; i < comPorts.Length; i++)
    comPorts[i] = Regex.Replace(comPorts[i], @"\D*(\d+)\D*", "$1");

But this regex also removes the COM.

Upvotes: 1

Views: 41

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

You may use

Regex.Replace(comPorts[i], @"(\d+).*", "$1")

See the regex demo

The (\d+).* regex will match and capture the first (leftmost) one or more digit text chunk and then .* will grab the rest of the string, and $1 will replace the whole match with the digits captured. Note you need to pass RegexOptions.Singleline as the last argument to Regex.Replace if the string can have more than one line.

Upvotes: 3

Related Questions