Search code examples
regexgoogle-sheetsarray-formulasgoogle-sheets-querygoogle-query-language

Is there a way to extract a particular string from a cell?


I'm trying to extract the value between round brackets of some substring that is part of a string separated by ,, and then add all those values.

For example:

Cell A1 : Text4(5),Text1(7)
Cell A2 : Text1(2)
Cell A3 : Text1(1),Text4(3),Text6(5)

Extract all the values between the round brackets of the Text1. That would be 7, 2 and 1. And the final result 10.

I've tried this with a single text (not separated by ,).

For example:

Cell A1 : Text1(4)    Cell B1 : Text1
Cell A2 : Text3(2)
Cell A3 : Text1(6)

In this case, by searching Text1 it gets the values 4 and 6 and shows the result 10.

=SUM(ARRAYFORMULA(VALUE(
    REGEXEXTRACT(
        SPLIT(
            QUERY(A1:A3,"select A where A contains '"&B1&"'")
        ,",")
    ,"[\[\(](.*)[\)\]]"))))

But I don't have any idea of how to get the value when there are more elements in the string. Tried with another query inside but had no luck.


Solution

  • =ARRAYFORMULA(SUM(REGEXEXTRACT(QUERY(TRANSPOSE(SPLIT(TEXTJOIN(",", 1, A1:A), ",")), 
     "where Col1 contains 'Text1'", 0), "\((\d+)\)")*1))
    

    0