EN
FRENCH
繁体中文
Regex (Regular Expression) is a sequence of characters that defines a search pattern for matching, extracting, or replacing text.
Regex is widely used in programming, data validation, log analysis, and web scraping. It helps developers identify specific information without manually examining every line of text.
Regex uses special characters and rules to describe text patterns.
A typical process includes:
For example, the pattern \d+ matches one or more consecutive digits.
| Symbol | Meaning | Example |
|---|---|---|
. |
Any character except newline by default | a.c |
\d |
A digit | \d{3} |
\w |
A word character | \w+ |
\s |
A whitespace character | \s+ |
* |
Zero or more repetitions | a* |
+ |
One or more repetitions | a+ |
? |
Zero or one occurrence | colou?r |
^ |
Start of a string or line | ^Hello |
$ |
End of a string or line | end$ |
Regex behavior can vary slightly between programming languages and regex engines.
Basic string matching searches for exact text, while regex supports flexible patterns.
For example, string matching can find 2026, while regex can match different four-digit years.
Regex is useful for extracting patterned information from collected web content.
For example, a scraper may use regex to identify product codes, prices, or dates within plain text.
However, structured webpage elements are generally better handled with HTML parsers such as Beautiful Soup or Cheerio.
Regex works best as a complementary tool for processing extracted text.
The following Python example extracts prices from a text string:
import re
text = "Mouse: $29.99, Keyboard: $49.50"
pattern = r"\$\d+\.\d{2}"
prices = re.findall(pattern, text)
print(prices)
Output:
['$29.99', '$49.50']
The expression matches a dollar sign, one or more digits, a decimal point, and exactly two decimal digits.
This approach can help extract consistently formatted values from product descriptions or other text.
Regex is a powerful pattern-matching tool for searching, validating, extracting, and replacing text.
It is useful in programming, data cleaning, and web scraping, especially when information follows predictable formats. For complex structured documents, regex should be combined with appropriate parsing tools.
Partenariat