regexios-shortcut

RegEx: Omit first single zero in flight numbers


I need a RegEx to format flight numbers to keep the letter code and the following digits, but omit the leading zero if it stands alone and the total number of digits is at least four. This is used in iOS Shortcuts which is a simplified workflow with actions. I can use a match action with RegEx. Examples of desired outputs:

SK0498 should return SK498 (total digits = 4 = omit the single leading zero)

AA007 should still return AA007 (because the leading zeros are double, and total digits is only 3)

UA2138 returns UA2138 (no leading zeros involved)

BA023 should return BA023 (keep the zero because total number of digits is only 3), however BA0234 should return BA234 (total digits is 4 with a single leading zero that should be omitted).

I’m not good with RedEx but so far I’ve figured out (?=0*)(00)*([1-9][\d]*). This correctly omits the first zero as long as it’s not double but I’m only half way there. I also want it to return the letter code, as well as honoring the minimum 4 digit rule for the leading zero to be omitted. (If the string has 4 digits with a single leading zero, omit the first, otherwise keep it). If this is even possible with this many criteria, how does it need to look?


Solution

  • If you want to omit the first single zero, you could use a capture group for the leading uppercase chars and use that group in the replacement:

    \b([A-Z]+)0(?=[1-9]\d{2}\b)
    

    The pattern matches:

    Regex demo

    If there is a minimum 4 digit rule, you can omit the last word boundary, and assert at least 2 digits:

    \b([A-Z]+)0(?=[1-9]\d{2})
    

    If there can be 3 digits to the right with a leading zero, and you want to remove the first zero only:

    \b([A-Z]+)0(?=\d{3}\b)
    

    Regex demo