Search code examples
regexalphanumeric

RegEx to get the alphabets or alphabets including the last digit with space


I have following strings:

Hyderabad RTC K1 1991-1998
Hyderabad RTC KK 1876-1897
Al Test K5 1876-9876

So, I want to get only the first part other than numbers from the above strings like:

Hyderabad RTC K1
Hyderabad RTC KK
Al Test K5

I have tried this ^[a-z]*([0-9] )?$ RegEx thinking that there will be any no of characters followed by a number and space or not.


Solution

  • You could use a capturing group to match any number of words ending with LetterNumber or both Letter followed by the digits-digits part:

    ^([A-Za-z]+\d*(?: [A-Za-z]+\d*)+) \d+-\d+$
    

    Regex demo

    Without the necessity to match the digits separated by a hyphen at the end, you can omit the capture group and the last part:

    ^[A-Za-z]+\d*(?: [A-Za-z]+\d*)*
    

    Regex demo