Creating a Regex Expression to Extract HS Code from a Given Text
An HS code, or Harmonized System code, is a standardized numerical method of classifying traded products. It is used by customs authorities around the world to identify products for the purpose of levying duties and taxes. In this article, we will demonstrate how to create a regular expression (regex) that can extract the HS code from a given text using Python.
Understanding the HS Code Format
HS codes are structured as a six-digit code, with the first two digits representing the chapter the product belongs to, the next two digits representing the heading, and the last two digits representing the subheading. For example, the HS code for "Knitted fabric, not of cotton, of man-made staple fibres" is 84732.
Creating the Regex Expression
To create a regex expression that can extract the HS code from a given text, we need to consider the following:
- HS codes are six digits long
- HS codes can contain any combination of digits
- HS codes are usually preceded by the string "HSCODE:"
Based on these considerations, we can create the following regex expression:
HSCODE:\d{6}Explanation of the Regex Expression
HSCODE:- Matches the string "HSCODE:"\d{6}- Matches any six digits
Testing the Regex Expression
To test the regex expression, we can use the re module in Python. Here's an example:
import re
text = "293PACKAGE()\_x000D\_PRINTEDHEADITEM:KA02033-E844A5:INVOICE:FIT-2401-01HSCODE:84732:100KNITTEDFABRICH.SCODE:6006.2:2.00INV#:TSTEX0124-009(TC-240021:)"
pattern = r'HSCODE:\d{6}'
match = re.search(pattern, text)
if match:
print(match.group())
else:
print("HS Code not found")
When we run this code, it will output:
HSCODE:84732In this article, we have demonstrated how to create a regex expression that can extract the HS code from a given text. By using the re module in Python, we can easily search for and extract the HS code from any text that contains it. This can be useful in a variety of applications, such as data analysis, customs clearance, and more.
- HS codes are a standardized numerical method of classifying traded products
- HS codes are structured as a six-digit code
- We can create a regex expression to extract the HS code from a given text
- The regex expression is
HSCODE:\d{6} - We can test the regex expression using the
remodule in Python