Output of regular expression is "undefined"

I am trying to get the invoice number of a WooCommerce order by using a regular expression.

The invoice number is returned in the meta_data from the Woocommerce Order Updated piece.

The part of the meta data that contains the invoice number would look like this:

    {
      "id": 45338,
      "key": "_wcpdf_invoice_date_formatted",
      "value": "2024-09-10 21:44:15"
    },
    {
      "id": 45339,
      "key": "_wcpdf_invoice_number",
      "value": "13100"
    },
    {
      "id": 45340,
      "key": "_wcpdf_invoice_number_data",
      "value": {
        "number": 13100,
        "formatted_number": "13100",
        "prefix": "",
        "suffix": "",
        "document_type": "invoice",
        "order_id": 1600,
        "padding": ""
      }
    },

I’m using the following regular expression to get the invoice number:

/"key":\s*"_wcpdf_invoice_number",\s*"value":\s*"(\d+)"/

The regex is working perfectly when I test it on regex101.com, but for some reason I can’t manage to get it to work in the Text Helper.

Any ideas to what I am doing wrong?

No one?

@abuaboud If I’m not mistaken, you are an AP support employee, correct? Do you have any suggestions to how I can solve this issue?

Hi @MathiasHoffmann

Sorry didn’t notice this

I will move this to known issues, in mean time you can use “Ask AI” feature in the code piece and ask it to extract this regex, It should give you a working example

After a lot of trial and error, I finally got it to work as intended. It was a good suggestion to use the code piece and simply use a bit of javascript to get the invoice number.
I did try the the AI helper, but the code it returned didn’t work, so I had to write it myself.

If others are facing a similar issue, this is the code I ended up with:

export const code = async (inputs) => {
  
function getInvoiceNumber(data) {
    const dataString = (typeof data === 'string') ? data : JSON.stringify(data);
    const regex = /"key":\s*"_wcpdf_invoice_number",\s*"value":\s*"(\d+)"/;
    const match = dataString.match(regex);

    if (match && match[1]) {
        return match[1];
    }
    return null;
}

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.