Creating a Regex Expression to Extract HS Code: Digits (Exclude Digits*) from a Given Text

Abstract: Extract HS codes from text while excluding specific digits using regex character classes and word boundaries.

Created: 2026-08-04 by

To extract Harmonized System (HS) codes from text while excluding specific digits, use a regex pattern that matches the standard 6 to 10 digit structure but employs negative lookahead or character class exclusions. For example, if you need to exclude the digit '9', use [0-8] instead of [0-9]. This approach ensures precise extraction without capturing invalid sequences.

Understanding HS Code Structure

Harmonized System codes are internationally standardized numeric methods for classifying traded products. They typically consist of six digits, though some countries extend them to eight, ten, or even twelve digits for further specificity. The first two digits represent the chapter, the next two the heading, and the following two the subheading. Understanding this hierarchical structure is crucial when building a regular expression because it defines the length constraints your pattern must enforce. Most HS codes found in general text will be either six digits long or ten digits long. A six-digit code looks like 123456, while a ten-digit national extension might look like 1234567890. When extracting these from unstructured data, such as PDFs, emails, or web pages, you must ensure your regex does not accidentally capture partial numbers or adjacent unrelated digits. This requires careful boundary handling to isolate the exact sequence intended as the HS code.

Constructing the Base Pattern

The foundation of any HS code regex is a sequence of digits. In most programming languages, including Python, JavaScript, and Java, the shorthand \d represents any single digit from 0 to 9. To match a six-digit code, you would typically use \d{6}. However, this simple pattern is dangerous because it can match part of a longer number. For instance, in the string 1234567890, \d{6} might match 123456, leaving 7890 unmatched, or it might behave unpredictably depending on the engine's greedy behavior. To prevent matching substrings of larger numbers, you should use word boundaries or lookarounds. Word boundaries (\b) are useful when the HS code is surrounded by non-word characters like spaces or punctuation. The pattern \b\d{6}\b works well for standalone six-digit codes. For ten-digit codes, you would use \b\d{10}\b. If you want to match both lengths simultaneously, you can combine them using alternation: \b\d{6}\b|\b\d{10}\b. This ensures that only complete codes of the expected lengths are captured. Regex: Extracting the Last 5 Words of Every Paragraph in Documents demonstrates similar boundary principles when isolating specific segments of text, which applies directly to isolating numeric codes from surrounding prose.

Excluding Specific Digits

The core requirement of your task is to exclude certain digits. Regular expressions allow you to define custom character classes. Instead of using \d (which means 0-9), you can explicitly list the allowed digits. For example, if you want to exclude the digit '9', you would use the character class [0-8]. This class matches any digit from 0 through 8, effectively rejecting any occurrence of '9'. If you need to exclude multiple digits, such as '9' and '5', you can construct a more complex character class. One method is to list all allowed digits: [01234678]. Another method, supported by many modern regex engines, is to use negated character classes with subtraction, though support varies. The most portable and clear approach is to explicitly list the allowed digits. For a six-digit code excluding '9', the pattern becomes \b[0-8]{6}\b. For a ten-digit code, it becomes \b[0-8]{10}\b. You can also use negative lookahead assertions to achieve exclusion dynamically. For example, (?!\d*9)\d{6} checks that the upcoming six digits do not contain a '9'. This is more flexible if the set of excluded digits changes frequently, but it is computationally heavier than simple character classes. For static requirements, explicit character classes are faster and easier to read.

Handling Edge Cases and Validation

When applying these patterns, consider the context in which the HS codes appear. Sometimes, HS codes are prefixed with letters or symbols, such as "HS: 123456" or "Code: 123456". In these cases, strict word boundaries might fail if the prefix is attached without a space. You may need to adjust your pattern to allow optional preceding characters. For example, (?:^|[^0-9])([0-8]{6})(?=[^0-9]|$) uses lookbehind and lookahead to ensure the code is not part of a larger numeric string, regardless of surrounding non-digit characters. It is also important to validate the extracted codes against known valid ranges if possible. While regex can filter out invalid formats, it cannot verify if a code actually exists in the official tariff schedule. For robust applications, combine regex extraction with a database lookup or an API call to confirm the validity of the extracted HS code. This two-step process ensures high accuracy in data processing pipelines. Handling Unicode Characters in Excel for Text from Hindi Language highlights the importance of character encoding awareness, which is equally critical when parsing text files that may contain mixed scripts or special formatting around numeric codes.

Implementation Examples

In Python, you can use the re module to find all matches. Here is an example for extracting six-digit codes excluding '9':
import re

text = "Product A has HS code 123456. Product B is 123459."
pattern = r"\b[0-8]{6}\b"
matches = re.findall(pattern, text)
print(matches)  # Output: ['123456']
This script finds all occurrences of six digits between 0 and 8, ignoring the second code because it contains a '9'. Adjust the pattern based on your specific exclusion rules and desired code length. Always test your regex against a diverse set of sample texts to ensure it handles edge cases correctly.

Frequently Asked Questions

Can I exclude digits using a negative lookahead?

Yes, you can use negative lookahead assertions like (?!\d*9) to ensure a specific digit does not appear in the match. This method is dynamic but slower than using explicit character classes. It is best suited for complex exclusion rules where listing allowed digits is cumbersome.

What if the HS code is followed by a decimal point?

Standard HS codes are integers, so decimals are not part of the code itself. Ensure your regex does not include the dot in the match group. Use a lookahead like (?=\D|$) to assert that the next character is not a digit, preventing partial matches if the number is formatted with decimals elsewhere.

How do I handle HS codes with hyphens?

Hyphens are sometimes used for readability (e.g., 1234-56). If your source text includes them, modify your pattern to optionally match hyphens, such as \b[0-8]{4}-?[0-8]{2}\b. Be cautious as this increases the risk of false positives. Validate the output format separately if needed.

Is there a performance difference between \d and [0-9]?

In most modern regex engines, \d and [0-9] perform similarly for ASCII digits. However, \d can match other Unicode digit characters depending on the engine settings. Using [0-9] or explicit ranges like [0-8] ensures you only match ASCII digits, providing consistent behavior across different platforms.

Can I extract HS codes from PDF files directly?

Regex operates on plain text strings. You must first extract the text content from the PDF using a library like PyPDF2 or pdfplumber. Once the text is extracted into a string variable, you can apply your regex pattern to find the HS codes. Layout analysis may be required if the text extraction order is disrupted.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More