How to extract a number at a specified position from a numeric string (e.g., extract the batch number from the product code)?

Calendar 81

In daily website operations, we often encounter situations where we need to handle various encodings or IDs, such as product codes, order numbers, batch numbers, etc., which often contain multiple segments of information, and we may only need to extract a part of the numbers.For example, from the complex product code "PROD20230815BATCH007", we just want to quickly obtain the batch number "007".

AnQi CMS, with its flexible content model and powerful template tag system, can easily meet such demands.Next, we will discuss how to use the built-in filter function of Anqi CMS to accurately extract the specified digits from a numeric string.

Step 1: Preparation - Define Content Model and Fields

Firstly, we need to ensure that your product codes and other information are stored in the Anqi CMS content model. If you do not have a dedicated field to store these codes, you can set it up through the following steps:

  1. Log in to the Anqi CMS backend, navigate to the 'Content Management' under 'Content Model'.
  2. You can choose to modify the existing content model (such as "product model" or "article model") or create a brand new content model.
  3. On the selected model editing page, find the 'Content Model Custom Fields' section.In here, you need to add a new field, such as named "Product Code", the field type is recommended to choose "Single Line Text".Thus, when publishing or editing product content, you can enter the complete product code in this field.

Assuming we have created a namedproduct_codeThe custom field, used to store product codes.

Step two: Call the product code in the template.

On our website frontend, whether it's the product detail page or the product list page, we first need to obtain the field value that contains the complete encoding. Anqi CMS providesarchiveDetailandarchiveListTags to help us achieve this.

If you are on the product detail page (usually corresponding to)detail.htmltemplate), you can directly go througharchiveDetailtags to get the current product'sproduct_codefield value:

{% archiveDetail productCode with name="product_code" %}
{% set fullProductCode = productCode %}

If you are on the product list page (usually correspondinglist.htmltemplate), you need toarchiveListget each product'sproduct_codefield value:

{% archiveList archives with moduleId="你的产品模型ID" type="page" limit="10" %}
    {% for item in archives %}
        {% set fullProductCode = item.product_code %}
        {# 接下来在这里处理 fullProductCode #}
    {% endfor %}
{% endarchiveList %}

Now, we have stored the complete product code infullProductCodeIn the variable, the next step of number extraction can be performed.

The third step: extract the number at the specified position -get_digitThe filter takes action

Anqi CMS is built-in with a very practicalget_digitA filter specifically designed to extract a single digit from a numeric string.This filter starts counting positions from the 'last digit' of the number string, with the position parameter starting from 1.

For example, the product code of our goods isPROD20230815BATCH007we want to extract the last digit of the batch number "7".

The usage is as follows:

{% set productCode = "PROD20230815BATCH007" %}
{% set lastDigit = productCode|get_digit:1 %}
<p>批次号的最后一位是:{{ lastDigit }}</p>

{% set thirdFromLastDigit = productCode|get_digit:3 %}
<p>批次号的倒数第三位是:{{ thirdFromLastDigit }}</p>

After this code runs,lastDigitit will be7,thirdFromLastDigitit will be0.

It should be noted that,get_digitThe filter is mainly used to extract individual numeric characters. If your product code contains non-numeric characters, and you try to extract the position corresponding to a non-numeric character,get_digitIt will try to convert it to the corresponding ASCII value and subtract 48, which may not be the result you expect. Therefore,get_digitIt is most suitable to use when determining the target position is a numeric character.

Step 4: More complex scenarios and general methods:sliceFilter

If we need to extract not a single number, but a continuous sequence of numbers (such as "007"), or product codes mixed with letters and numbers, and we need to extract a specific substring, thensliceThe filter is a more generic choice.

sliceThe filter is used to extract elements from a string or an array at specified positions. It usesfrom:toformat to define the range of extraction, wherefromIs the starting index (counting from 0),toIs the end index (does not include the character at the index position).

Continue with the product codePROD20230815BATCH007For example:

  • PCorresponding index 0
  • RCorresponding index 1
  • ...
  • 0(The first digit of the batch number) corresponding index 17
  • 0(Batch number second digit) corresponds to index 18
  • 7(Batch number third digit) corresponds to index 19

To extract batch number007It starts at index 17 and ends at index 20 (excluding the character at index 20).

{% set productCode = "PROD20230815BATCH007" %}
{% set batchNumber = productCode|slice:"17:20" %}
<p>提取的完整批次号是:{{ batchNumber }}</p>

After this code runs,batchNumberit will be007.

sliceThe filter is very flexible when handling strings containing mixed characters, as long as you can determine the start and end index positions, you can accurately extract the required substring.

Summary

By following these steps, we see that Anqi CMS provides powerful template tags and filters, making it simple and intuitive to extract specific information from complex numeric strings. Whether it is to extract a single number or a continuous segment of numbers, you can choose according to your specific needsget_digitorsliceFilter. This flexibility greatly improves the efficiency of content operation, allowing your website to display and manage product data more intelligently.


Frequently Asked Questions (FAQ)

1. If my product code contains both letters and numbers,get_digitCan the filter accurately extract the numbers I want?

get_digitThe filter may behave less intuitively when encountering non-numeric characters, it will try to convert the characters to ASCII values for processing. Therefore, if your product code contains letters and numbers and you need to extract the numeric positions that may correspond to non-numeric characters, or if you need to extract multiple digits, it is recommended to use a more generalslicefilter.sliceThe filter will directly cut the substring according to the character index range you specify, whether it is a number or a letter, it can be accurately obtained.

2. I want to extract the batch number not at a fixed position, but by some delimiter (such as a hyphen “-”) identification, does AnQi CMS have a way to do this?

Of course! If the batch number is defined by a specific delimiter, you can usesplitThe filter splits the entire string into an array and then retrieves based on the batch number at the position in the array. For example, the product code isPROD-2023-007, Batch number "007" is the third part, you can do this:

{% set productCodeWithDelimiter = "PROD-2023-007" %}
{% set parts = productCodeWithDelimiter|split:"-" %} {# 拆分成 ["PROD", "2023", "007"] #}
{% set batchNumber = parts[2] %} {# 获取第三部分,索引为2 #}
<p>通过分隔符提取的批次号是:{{ batchNumber }}</p>

3. Extracted numbers (such as inventory quantities) need to perform addition, subtraction, multiplication, and division, can they be operated directly in the template??

Yes, AnQi CMS supports basic arithmetic operations in templates. You can useaddfilters for addition, or directly apply+/-/*//operators in expressions. For example:

`twig {% set stock = “100”|integer %} {# Convert string to integer #} {% set newStock = stock|add:50 %} {# 100 + 50 = 150 #}

The stock quantity after increase is: {{ newStock }}

{% set price = “199.99”|

Related articles

What type of result will be obtained when the `add` filter processes addition of different data types?

In AnQi CMS template development, we often encounter scenarios where we need to process and transform data.(Filter) is a powerful feature that was born for this purpose, which can help us format, modify, or calculate variables with concise syntax.Today, let's delve deeply into one very practical filter: `add`, especially its specific performance in handling the addition of different data types.### `add` filter: Simplifies the combination of numbers and text The core function of the `add` filter, as the name implies, is to add two values together

2025-11-08

How to perform addition or concatenation operations between numbers and strings in AnQiCMS templates?

During the process of building a website, we often encounter the need to perform arithmetic operations on numbers in templates, or to concatenate different string content to form new text.For AnQiCMS users, understanding how to efficiently implement these operations in the template engine is the key to enhancing the flexibility of content display and development efficiency.AnQiCMS is a powerful template engine, drawing inspiration from Django's design philosophy, providing intuitive and feature-rich tags and filters to meet these needs.#### AnQiCMS Template Basic

2025-11-08

What are some common application scenarios for the `cut` filter in cleaning string data?

In website content management, we often encounter situations where we need to clean and format string data.Whether it is form information submitted by the user or content imported from the outside, the data may contain extra spaces, unnecessary punctuation marks, or even other special characters.These uninvited guests not only affect the aesthetics of the data, but may also interfere with subsequent data processing and display.AnQi CMS provides rich template filters to help us solve these problems, where the `cut` filter is a concise and efficient tool

2025-11-08

How can extra spaces or special characters be removed from user input or dynamic content?

In website operation, we often face an indispensable challenge: how to ensure that the user input or dynamically generated content is clean, tidy and safe.Extraneous spaces, invisible control characters, even unprocessed special symbols, may affect the layout beauty of the website, the search engine optimization (SEO) effect, and even bring potential security risks.AnQiCMS as an efficient and customizable enterprise-level content management system has fully considered these operational pain points.It provides a series of powerful and flexible template filters

2025-11-08

What will the `get_digit` filter return when processing non-numeric strings?

In AnQiCMS template development, we often use various filters to process data, where the `get_digit` filter is a convenient tool for extracting specific digits from numbers.However, when we turn our attention to a more common but potentially misunderstood scenario - that is, when the `get_digit` filter encounters a **non-numeric string**, its behavior becomes less obvious.Let's review the performance of the `get_digit` filter when dealing with pure numbers.When the data is of a standard numeric type

2025-11-08

How to determine if a number can be evenly divided by another number in AnQiCMS templates?

In web content display, we often encounter situations where we need to adjust the layout or display logic of content based on the characteristics of some numbers.For example, we may need to insert an advertisement every few articles, or make even and odd rows of the table display different background colors, or perform special operations when the list loops to a specific position.In the AnQiCMS template system, based on the Django template engine syntax, it provides a very practical filter that can easily meet this requirement.This filter is `divisibleby`

2025-11-08

Can the `divisibleby` filter be used to implement alternating row colors or other conditional styles in a loop?

In the daily operation of website content, how to make the list data more readable and visually attractive is a key factor in improving user experience.AnQiCMS (AnQiCMS) offers a flexible template engine, providing rich possibilities for content display.Today, let's talk about a very practical template filter——`divisibleby`, and see how it helps us achieve alternate row coloring or other conditional styles in loops.## Get to know the `divisibleby` filter AnQi CMS template system

2025-11-08

How to format a Unix timestamp into a readable date and time string?

In website content management, the way time is presented is crucial to user experience.Although the system may prefer a unified and efficient Unix timestamp format for background data processing, for visitors, a string of random numbers is obviously not as intuitive and easy to understand as AnQi CMS knows this and provides a simple and powerful tool to solve this problem.### Unix timestamp: The 'time language' in the database Unix timestamp, in short

2025-11-08