Search code examples
regexregular-language

RegEx that keeps the first 3 characters and deletes the rest


I have an identifier that contains letters or digits and dashes. What I would like to do is to keep the first 3 letters before the first dash and delete the rest and then keep the 2 first letters after the first dash.

For instance, I have the following id :

9D3236A9-B496-4597-87E4-3A3FB69D07BF

The output ID should be : 9D3B445873A3.

I have tried:

^.{3}\-

but nothing happens. Can you please help with that?


Solution

  • You may use

    ^([A-Za-z0-9]{3})[A-Za-z0-9]*|-([A-Za-z0-9]{3})[A-Za-z0-9]*$|-([A-Za-z0-9]{2})[A-Za-z0-9]*
    

    Replace with $1$2$3. See the regex demo.

    Details

    • ^ - start of string
      • ([A-Za-z0-9]{3}) - Group 1 ($1 in the replacement): 3 alphanumeric chars
      • [A-Za-z0-9]* - 0+ alphanumerics
    • | - or
      • - - a hyphen
      • ([A-Za-z0-9]{3}) - Group 2 ($2 in the replacement): 3 alphanumeric chars
      • [A-Za-z0-9]* - 0+ alphanumerics
      • $ - end of string
    • |
      • - - a hyphen
      • ([A-Za-z0-9]{2}) - Group 3 ($3 in the replacement): 2 alphanumeric chars
      • [A-Za-z0-9]* - 0+ alphanumerics.