简体   繁体   中英

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.

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM