GrepBoard/Manuals
605 manuals ·

Extract Order IDs and Amounts with Sheets REGEXEXTRACT

·Tested on Gemini 3.8 Flash · 2026-10·Test scope ↓·5 steps

Extract order IDs and currency amounts from messy customer notes using Google Sheets REGEXEXTRACT formulas, and verify edge cases with Python.

When customer service notes contain order numbers and transaction totals mixed together in a single text column (such as "Refund requested for order ORD-2026-00451 amount $120.00 processed"), manual data entry is slow and standard delimiter-based splitting fails. Using Google Sheets REGEXEXTRACT with tailored regular expressions isolates the required identifiers into dedicated columns. The broader workflow for turning raw text into verified tabular data is also detailed in table extraction and column validation.

[1] Prepare test records with edge cases. Generating formulas without diverse edge cases produces fragile expressions that fail silently or produce #N/A errors across large sheets. Set up 25 representative test rows in column A: 15 standard notes, 3 records missing order IDs, 2 records containing multiple order IDs, and 5 records with varied pricing formats or missing totals.

RowColumn A (Customer Note)Note Type
1Refund requested for order ORD-2026-00451 amount $120.00 processed.Standard record
2Inquiring about shipping delay, no order ID provided.Missing order ID
4Cancel order ORD-2026-00103 full refund of $1,500.00 needed.Comma in amount
5Return previous ORD-2026-00012 and charge new ORD-2026-00345 amount $45.50.Two order IDs
7Partial refund approved for ORD-2026-00781 credit $89.00 waiting.Standard record
9Missing accessory inquiry for ORD-2026-00999 no charge.Missing amount

[2] Construct the prompt. Following OpenAI guidance on prompt engineering, providing examples across a diverse range of possible inputs prevents the model from overfitting to simple patterns. In accordance with Google Workspace principles on formula generation, request step-by-step regex breakdowns alongside the formula to evaluate boundary conditions and error handling.

text
Column A in Google Sheets contains unstructured customer support notes.Write Google Sheets formulas to extract the {identifier name} and the {numeric value name} into separate columns. [Target Formats]1. {identifier name}: {identifier format description} (e.g., {identifier sample})2. {numeric value name}: {numeric format description} (e.g., {numeric sample} -> extract as clean number or text) [Sample Input Notes - {sample row count} Rows]{sample records} [Requirements]- Google Sheets formula for cell B2 to extract {identifier name} using REGEXEXTRACT.- Google Sheets formula for cell C2 to extract {numeric value name} using REGEXEXTRACT (including conversion to a numeric value).- How to handle #N/A errors when an identifier or numeric value is missing.- Explain which identifier is matched when a note mentions multiple identifiers.- Provide a concise step-by-step breakdown of each regular expression pattern.

[3] Execute the prompt with Gemini. Run the model through an isolated execution environment outside the main repository tree.

console
$ agy -p "$(cat run/en-1.prompt.txt)" --model gemini-3.8-flash --effort high --output-format text > run/en-1.out.txt

Verify the key formulas and explanations directly from the output log:

output
Here are the Google Sheets formulas and regex breakdown for extracting the Order ID and Amount. --- ### 1. Formula for Cell B2 (Order ID) =IFERROR(REGEXEXTRACT(A2, "ORD-\d{4}-\d{5}"), "") * Optional (Case-Insensitive): If notes might have lowercase ord-, use:  =IFERROR(REGEXEXTRACT(A2, "(?i)ORD-\d{4}-\d{5}"), "") --- ### 2. Formula for Cell C2 (Amount converted to Numeric Value) =IFERROR(VALUE(SUBSTITUTE(REGEXEXTRACT(A2, "\$([0-9,]+(?:\.[0-9]{2})?)"), ",", "")), "")…### 4. Behavior with Multiple Order IDs (e.g., Row 5) Row 5: "Return previous ORD-2026-00012 and charge new ORD-2026-00345 amount $45.50." * Default behavior: REGEXEXTRACT scans from left to right and returns the first match it encounters. In Row 5, it returns ORD-2026-00012.…

Running the exact prompt a second time (run/en-2.out.txt) yielded the same B2 formula. In cell C2, the decimal capture group shifted from (?:\.[0-9]{2})? (exactly two decimals) to (?:\.[0-9]+)? (one or more decimals), and gave an alternative formula using NUMBERVALUE. That function is not in Google's official Sheets function list (VALUE is), so do not adopt the alternative; IFERROR would also hide the unsupported-function error as a blank.

[4] Apply the formulas and verify row by row. Do not wrap the formulas in IFERROR at first, or you cannot tell a pattern that failed from a note that really has no data. Enter =REGEXEXTRACT(A2, "ORD-\d{4}-\d{5}") and =REGEXEXTRACT(A2, "\$([0-9,]+(?:\.[0-9]{2})?)") without IFERROR and count the #N/A errors. The counts below come from counting NONE expectations in this guide's 25-row sample; they were not obtained by running the formulas in Sheets.

1. Column B (Order ID): 3 sample rows have no order ID (rows 2, 6, and 23), so #N/A should appear in exactly those rows. 2. Column C (Amount): 3 sample rows have no amount (rows 2, 9, and 25), so #N/A should appear in exactly those rows. 3. Once the counts match, wrap each formula in IFERROR(..., ""). 4. Apply the same patterns to the 25 rows with Python re and compare with the expected values. The script reads the first two patterns (order ID, then amount) from the REGEXEXTRACT(A2, "...") formulas in the model's answer file.

run/check.py
#!/usr/bin/env python3"""usage: check.py data.tsv ko|en [model_output.txt]Python re on sample notes vs expected (note, order, amount) in the TSV. With a model output file, thepatterns come from its first two REGEXEXTRACT(A2, "...") formulas. Not Google Sheets (RE2) and not the full formulas."""import sys, re if len(sys.argv) < 3:    sys.exit(__doc__)tsv, lang = sys.argv[1], sys.argv[2]order_pat = r"ORD-\d{4}-\d{5}"amount_pat = r"([0-9,]+)\s*원" if lang == "ko" else r"\$([0-9,]+(?:\.[0-9]{2})?)"if len(sys.argv) > 3:    text = open(sys.argv[3], encoding="utf-8").read()    pats = re.findall(r'REGEXEXTRACT\(\s*A2\s*,\s*"((?:[^"\\]|\\.)*)"', text)    order_pat = next((p for p in pats if "ORD" in p), None)    amount_pat = next((p for p in pats if "ORD" not in p), None)    if not order_pat or not amount_pat:        sys.exit("FAIL: could not find both patterns in the model output")print(f"order pattern : {order_pat}")print(f"amount pattern: {amount_pat}") order_re, amount_re = re.compile(order_pat), re.compile(amount_pat)rows = [l.rstrip("\n").split("\t") for l in open(tsv, encoding="utf-8") if l.strip()]if not rows:    sys.exit("FAIL: empty input")bad, none_order, none_amt = 0, 0, 0for n, r in enumerate(rows, 1):    if len(r) != 3:        print(f"FAIL row {n}: expected 3 tab-separated columns, got {len(r)}")        bad += 1        continue    note, want_order, want_amt = [x.strip() for x in r]    m = order_re.search(note)    got_order = (m.group(m.lastindex or 0) if m else "NONE")    a = amount_re.search(note)    got_amt = (a.group(a.lastindex or 0).replace(",", "") if a else "NONE")    none_order += got_order == "NONE"    none_amt += got_amt == "NONE"    if got_order != want_order or got_amt != want_amt:        bad += 1        print(f"MISMATCH row {n}:")        print(f"  Note: {note}")        if got_order != want_order:            print(f"  Order: expected '{want_order}', got '{got_order}'")        if got_amt != want_amt:            print(f"  Amount: expected '{want_amt}', got '{got_amt}'")print(f"\nResult: {len(rows)} rows checked, {len(rows) - bad} matched, {bad} mismatches.")print(f"Rows without an order ID: {none_order}, rows without an amount: {none_amt}")sys.exit(1 if bad else 0)

What this script checks is whether the regex patterns produce the expected values on the 25 sample rows. It does not run Google Sheets (RE2 behaviour) or the full formulas wrapped in IFERROR, VALUE, and SUBSTITUTE. The expected values were written by hand when the sample was made.

console
$ python3 run/check.py run/data.en.tsv en run/en-1.out.txtorder pattern : ORD-\d{4}-\d{5}amount pattern: \$([0-9,]+(?:\.[0-9]{2})?) Result: 25 rows checked, 25 matched, 0 mismatches.Rows without an order ID: 3, rows without an amount: 3

The patterns read from the second answer (en-2.out.txt, with (?:\.[0-9]+)? for the decimals) also matched all 25 rows (2 of 2). Three kinds of faulty input were tested: a changed amount, the later of two order IDs written as the expected value, and a changed number of digits in the amount (run/data.bad.en.tsv), plus an answer file whose order ID pattern ends in 4 digits instead of 5 (run/bad-pattern.out.txt). All exited with code 1 (not model output). The output for the wrong amounts and order ID:

console
$ python3 run/check.py run/data.bad.en.tsv enorder pattern : ORD-\d{4}-\d{5}amount pattern: \$([0-9,]+(?:\.[0-9]{2})?)MISMATCH row 1:  Note: Refund requested for order ORD-2026-00451 amount $120.00 processed.  Amount: expected '150.00', got '120.00'MISMATCH row 2:  Note: Return previous ORD-2026-00012 and charge new ORD-2026-00345 amount $45.50.  Order: expected 'ORD-2026-00345', got 'ORD-2026-00012'MISMATCH row 3:  Note: Partial refund approved for ORD-2026-00781 credit $89.00 waiting.  Amount: expected '890.00', got '89.00' Result: 3 rows checked, 0 matched, 3 mismatches.Rows without an order ID: 0, rows without an amount: 0

[5] Weak points observed, and fixes.

1. First-match extraction on multi-order notes: REGEXEXTRACT returns the first match (both answers said so). In row 5 ("Return previous ORD-2026-00012 and charge new ORD-2026-00345"), if the ID you need is the newer, later one, the earlier ID is returned.

  • Fix: To get the last ID, put .* before the capture group: =IFERROR(REGEXEXTRACT(A2, ".*(ORD-\d{4}-\d{5})"), ""). Applied to row 5 with Python re, it returned ORD-2026-00345 (run/optional_unit.out.txt).

2. Amounts without a dollar sign or with other currencies: \$([0-9,]+(?:\.[0-9]{2})?) needs a leading $. Notes such as "120.00 USD" or bare numbers would produce #N/A, which IFERROR turns into a blank. The 25-row sample has no such rows, so this was not tested.

  • Caution: Do not make the dollar sign optional ((?:\$)?([0-9,]+(?:\.[0-9]{2})?)). On row 1 it returned the year 2026 of the order ID instead of the amount (run/optional_unit.out.txt). Enter amounts without a symbol by hand or review them.

3. Boundaries on IDs and amounts: The order ID pattern ORD-\d{4}-\d{5} cuts the first 5 digits even when more digits follow, so ORD-2026-004511 (6 digits) comes back as ORD-2026-00451. The amount pattern \$([0-9,]+(?:\.[0-9]{2})?) has the same problem: $120.5 gives 120 and $120.567 gives 120.56 instead of an error or blank (run/data.edge.en.tsv, Python re). With the expectation set to "none" for these rows, the model's patterns give:

console
$ python3 run/check.py run/data.edge.en.tsv en run/en-1.out.txtMISMATCH row 1:  Note: Order ORD-2026-004511 refund $120.00 requested.  Order: expected 'NONE', got 'ORD-2026-00451'MISMATCH row 2:  Note: Refund $120.5 requested for ORD-2026-00451.  Amount: expected 'NONE', got '120'MISMATCH row 3:  Note: Refund $120.567 requested for ORD-2026-00451.  Amount: expected 'NONE', got '120.56' Result: 4 rows checked, 1 matched, 3 mismatches.Rows without an order ID: 0, rows without an amount: 0
  • Fix: Patterns that consume the characters on both sides, (?:^|[^0-9A-Za-z-])(ORD-\d{4}-\d{5})(?:[^0-9]|$) and \$([0-9,]+(?:\.[0-9]{2})?)(?:[^0-9.]|\.(?:[^0-9]|$)|$), passed all 4 edge rows and the original 25 rows (run/hardened.en.out.txt). They avoid lookarounds because RE2 is not known to support them, but they were not run in Sheets.

#spreadsheet#regexextract#google-sheets#gemini