3

I do Google sheets and I'm fighting with REGEXREPLACE function past few hours, in general I have this:

string1: "blah blah blah @abc blah @bcd blah blah"

And I want this:

string2: "@abc @bcd"

I try to extract it with REGEXEXTRACT(string1,"@[^\s]+") but this function won't work global, so I use REGEXREPLACE to replace everything else than @abc and @bcd to "", but to do that I need to negate @[^\s]+!
How to do that?

1
  • Also can try with regexreplace like this (@\S+\s*)|[^@]+ and replace with $1
    – Jonny 5
    Jul 27, 2015 at 4:35

3 Answers 3

4

I think this can helps (With $1 substitution):

/(?:.*?(@\S*))|(.*)/ig

[Regex Demo]

1
  • How can I accomplish this, but for extracting all instances of text inside brackets with "t-", e.g., [t- text here] (Note: there are other texts inside brackets, but with different letters, e.g., [a- text here] - we don't want these)
    – user3871
    Feb 3, 2019 at 21:19
1

(edit) I suggested the other answers wouldn't work in Sheets, but I didn't look at @shA.t's answer closely, which in fact works perfectly. This would be the Sheets implementation:

=REGEXREPLACE(L1,"(?:.*?(@\S*))|(.*)","$1")

My original answer:

Unfortunately I think the other answers won't work in the context of Google Sheets, which doesn't support "look-aheads" in spreadsheet function regex.

See if this works:

=ArrayFormula(TRIM(JOIN(" ",IFERROR(REGEXEXTRACT(SPLIT(L1," "),"^@.+")))))

1
  • 1
    I think I did test both, and as far as I remember both did work. I stayed with REGEXREPLACE (myStringHere,"(?:.*?(@\S*))|(.*)","$1") because I think it did filter out string exactly, the other solution is very close (I think some white spaces were let in). Anyway both work, thanks lots!
    – mmd
    Jul 28, 2015 at 3:02
0

Thank you shA.t ... I was trying to do a similar thing with JSON file extracting data fields using google sheets by including what I wanted then running into the restrictions of RE2 used by sheets. Using REGEXREPLACE and excluding what I didn't want worked like a charm, just substituted by trial and error till It was perfect

=REGEXREPLACE(L1,"(?:.*?{("guid":".*?")})|(.*)","$1")

demo

After looking at it closer I realized I wanted the headers to be removed as well, so the final RE2 is even simpler

(?:.*?:(".*?"))|(.*)

demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.