Extract, Replace, Match Nth Occurrence of a String or Number in Google Sheets

Published on

Get three formulas to extract, replace, and match the nth occurrence of a string/number in a phrase in Google Sheets. The formulas are based on Regexextract, Substitute, and Regexmatch respectively.

For replacing and matching nth occurrence, of course, we will use a specific word or number for the nth match/replace. But there is no point in extracting nth occurrence of a specific word, right?

So what we are going to do with our three (or more) different Google Sheets formulas are;

  • Extracting Nth Occurrence of a Non-Specific Word/Number.
  • Replacing Nth Occurrence of a Specific Word/Number.
  • Matching Nth Occurrence of a Specific Word/Number

Let’s begin with matching the nth occurrence of a string/number in Google Sheets.

RegexMatch Function to Match Nth Occurrence in Google Sheets

Here is the regular_expression, I mean the regex pattern, to match the nth occurrence of a number using RegexMatch in Google Sheets.

(?i)(?:.*?text){n}

Replace text with the ‘text’ that you want to match and ‘n’ with the number of occurrences.

Match Second Occurrence of a String

The following Regexmatch formula would match the second occurrence of the string ‘apple’ in cell A1.

=REGEXMATCH(A1,"(?i)(?:.*?apple){2}")
Match Nth Occurrence of a String in Google Sheets

The above formula is case insensitive. To make this regular_expressin case sensitive remove (?i) from the pattern.

The formula returns TRUE since the string ‘apple’ has the second occurrence in cell A1. If you put 4, then the formula would return FALSE as there is no fourth occurrence of the said string.

For an alternative solution to this formula please scroll down to see the “Bonus Tip”.

Match Second Occurrence of a Number

Here there are no changes in the formula except the number (text pattern) to match.

=REGEXMATCH(A1,"(?i)(?:.*?4.5){2}")

Formula matches the second occurrence of the number 4.5.

Replace Nth Occurrence with the Substitute Function in Google Sheets

Instead of Regex, I am using the Substitute function to replace the nth occurrence of a string or number in Google Sheets.

If you check the syntax of the Substitute function, you can understand that one of the argument in this function is the occurrence_number.

SUBSTITUTE(text_to_search, search_for, replace_with, [occurrence_number])

That means this Google Sheets function is built in to substitute the nth occurrence.

Replace Second Occurrence

Example:

Formula replaces the second occurrence of the country name ‘France’ with blank. This formula is case sensitive.

=SUBSTITUTE(A1,"France","",2)

Using this Substitute formula you can replace the nth occurrence of a number too.

Value in cell A1:

10, 20, 20, 30

Formula:

=SUBSTITUTE(A1,"20,","",2)

Output:

10, 20, 30

Bonus Tip – Matching the Nth Occurrence in the Substitute Way

We can use the Substitute function in Google Sheets for matching nth occurrence! Do you know how?

You can replace the Regexreplace formula under the above subtitle “Match Second Occurrence of a String” with my following Substitute formula.

=A1<>SUBSTITUTE(A1,"apple","",2)

RegexExtract Nth Occurrence of a Number in Google Sheets

I have the following phrase in a cell in Google Sheets.

“I have 20 pens and 30 pencils”.

If the above phrase is in cell A1, to extract the second number which is 30 from this, we can use the Regexextract function as follows in Google Sheets.

Extract Second Occurrence

=regexextract(A1,"(?:[^\d]*(\d+)){2}")

Since Regex is a text function, the returned number, i.e. 30, would be text formatted. Want the Regexextract output in number? Then use this formula.

=regexextract(A1,"(?:[^\d]*(\d+)){2}")*1

To change the second occurrence to nth, replace {2} with the number you want. I mean type {5} for the 5th occurrence.

If you simply want the second occurrence of a value (irrespective of the value, it can be a number or text) then use this Regex.

=regexextract(A1,"(?:\W*(\w+)){2}")

Use the above formulas to meet your requirements of extracting, replacing, and matching the nth occurrence of a value in Google Sheets.

Related Reading: Regex to Replace the Last Occurrence of a Character in Google Sheets.

Prashanth KV
Prashanth KV
Your Trusted Google Sheets and Excel Guide Prashanth KV brings a wealth of experience in Google Sheets and Excel, cultivated through years of work with multinational corporations in Mumbai and Dubai. As a recognized Google Product Expert in Docs Editors, Prashanth shares his expertise through insightful blogging since 2012. Explore his blog for practical tips and guidance on maximizing your spreadsheet skills.

Compare Two Tables for Differences in Excel

To compare two tables with similar data for differences, you can use the XLOOKUP...

Calculate Weighted Average in Pivot Table in Google Sheets

You can calculate a weighted average in a Pivot Table using a custom formula...

Summarize Data and Keep the Last Record in Google Sheets

In Google Sheets, we can summarize data (like sum, average, min, max, count) using...

How to Retrieve the Last Record in Each Group in Excel

As part of data analysis, you may need to retrieve the last record from...

More like this

Calculate Weighted Average in Pivot Table in Google Sheets

You can calculate a weighted average in a Pivot Table using a custom formula...

Summarize Data and Keep the Last Record in Google Sheets

In Google Sheets, we can summarize data (like sum, average, min, max, count) using...

Filter Data with Multi-Select Drop-Downs in Google Sheets

If you've started using multi-select drop-downs in Google Sheets, you may encounter challenges when...

5 COMMENTS

  1. Thanks a ton, Prashanth! That turned out to be the exact formula pattern I ended up coming up with too. So that’s validating!

    I was hoping there might be a pure regex solution without the 2 SUBSTITUTE steps, but it definitely works the way you’ve got it.

  2. Thanks for your articles! I’m struggling with a specific extraction and am hoping you can help!

    I want to sequentially extract each occurrence of whatever is inside quotation marks from a string.

    So say the string is: Jack and “Jill went” “up the hill” to fetch a “pail of water”

    I want to extract to an array each part that’s inside the quotes, i.e.:

    1. Jill went
    2. up the hill
    3. pail of water

    I’ve been able to extract what’s inside the quotes with REGEXEXTRACT, but it only gives me the first one.

    Thanks for any advice!

    • Hi, McKay Savage,

      The following formula works in my test when the string is in cell C3.

      =ArrayFormula(REGEXEXTRACT(SUBSTITUTE(SUBSTITUTE(C3,"""",">",{1;3;5}),"""","<",{1;3;5}), ">(.+)<"))

      Give it a try.

  3. How can I use regex to return the location of the nth occurrence of a string in a cell?

    Any help would be appreciated!

    • Hi, Katie,

      If you want to return the position of the nth occurrence of “Class” in cell A1, try the below formulas.

      Regex:

      =search("🐟",regexreplace(A1,"(?:.*?Class){n}","$0🐟"))-5

      Substitute:

      =search("🐟",substitute(A1,"Class","🐟 Class",n))

      Replace n with the nth position.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.