Phil
Phil

Reputation: 611

regex match everything up till last number

I have a couple of strings that look like this

EXT. 6TH STREET12B
EXT. HOSPITAL20
EXT. 20TH STREET 40AB

How do I match everything up till the last number starts. The result needs to be:

EXT. 6TH STREET
EXT. HOSPITAL
EXT. 20TH STREET

I'm not a regex expert at all. I tried a few things but nothing seems to come close.

Upvotes: 0

Views: 171

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460340

Here's a pure string method approach:

var digits = "0123456789".ToCharArray();
var trimEnd = digits.Concat(new[]{' ', '\t'}).ToArray(); // if desired
for (int i = 0; i < lines.Length; i++)
{
    string line = lines[i];
    int lastIndexOfDigit = line.LastIndexOfAny(digits);
    if (lastIndexOfDigit >= 0)
        line = line.Remove(lastIndexOfDigit).TrimEnd(trimEnd);
    lines[i] = line;
}

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174864

Use the greediness of *

@".*(?<=\D)(?=\d)"

or

@".*(?<!\d)(?=\d)"

DEMO

If you don't want to match the space which exists before the last number.

@".*(?<=[^\d\s])(?=\s*\d)"

DEMO

Upvotes: 1

Related Questions