Search code examples
regexvscode-snippets

I am trying to transform the file name (TM_FILENAME_BASE) but remove a key word from the middle of the text


For example I have a file named 'prefix-component.suffix.ts'. I would like the result to be PrefixSuffix with the word 'component' removed. I can make this work by using ${TM_FILENAME_BASE/(.*?)\\bcomponent\\b(.*)/${1:/pascalcase}${2:/pascalcase}/g}. ${1:/pascalcase} is everything before 'component' and ${2:/pascalcase} is everthing after. The problem is not all file names have the word 'component' in them so group 1 and 2 are empty in those cases. Is there a way to do this with 1 ${1:/pascalcase} with 'component' removed if it is present.


Solution

  • Make \bcomponent\b and the suffix collectively optional:

    ${
      TM_FILENAME_BASE
      /
        ^                             # Match at the start of the string
        (.*?)                         # anything, as few as possible,
        (?:                           # until we see
          (?:\bcomponent\b)           # 'component' as a full word
          (.*)                        # followed by anything,
        )?                            # both of which may or may not collectively present
        $                             # right before the end of the string.
      /
        ${1:/pascalcase}
        ${2:/pascalcase}
      /g
    }
    
    Before Prefix Suffix After
    prefix-component.suffix prefix- .suffix PrefixSuffix
    prefix.suffix prefix.suffix Nothing PrefixSuffix

    Try it on regex101.com.