Multiple regex matches in Google Sheets formula

后端 未结 5 2031
情歌与酒
情歌与酒 2020-12-01 17:08

I\'m trying to get the list of all digits preceding a hyphen in a given string (let\'s say in cell A1), using a Google Sheets regex formula :

=R         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 17:24

    You may create your own custom function in the Script Editor:

    function ExtractAllRegex(input, pattern,groupId) {
      return Array.from(input.matchAll(new RegExp(pattern,'g')), x=>x[groupId]);
    }
    

    Or, if you need to return all matches in a single cell joined with some separator:

    function ExtractAllRegex(input, pattern,groupId,separator) {
      return Array.from(input.matchAll(new RegExp(pattern,'g')), x=>x[groupId]).join(separator);
    }
    

    Then, just call it like =ExtractAllRegex(A1, "\d-", 0, ", ").

    Description:

    • input - current cell value
    • pattern - regex pattern
    • groupId - Capturing group ID you want to extract
    • separator - text used to join the matched results.

提交回复
热议问题