Home >Backend Development >C++ >Why is `\d` Slower Than `[0-9]` in C# Regex?

Why is `\d` Slower Than `[0-9]` in C# Regex?

Linda Hamilton
Linda HamiltonOriginal
2025-01-31 18:31:13240browse

Why is `d` Slower Than `[0-9]` in C# Regex?

C#regular expression

Slower than slower d [0-9] This article discusses a surprising discovery in the C#regular expression engine:

character type seems to be lower than the

character range efficiency, even if d is a super set of [0-9]. [0-9] d The difference between

and

d [0-9] The main reason for the difference in efficiency is the difference between these two characters:

:
    match any unicode number character. This includes not only standard numbers 0-9, but also other numbers used in different languages ​​and writing systems. For example, Persian numbers and Devanagari numbers are also
  • . d : d Only match the number 0-9. It is a compact representation of the character set .
  • The impact on performance [0-9] [0123456789] When matching the string with the regular expression, the regular expression engine needs to compare each character in the string with the specified character class. For , it must perform additional inspections to determine whether the character is a unicode number, which may be higher than the simple checking character in the range of 0-9.
Test verification

The test code provided by demonstrates this performance difference. On the more than 10,000 random string (each string contains about 50%of the numbers), the following results are obtained:

d regular expression

: 00: 00: 00.2141226 (slower)

Regular expression : 00: 00: 00.1357972 (Fast)

Regular expression

: 00: 00: 00.1388997 (slightly slower than
    )
  • d
  • Conclusion
  • [0-9]
  • Although is a convenient abbreviation of
  • , it is not always the best choice in terms of performance. If you only need to match the standard number 0-9, it is recommended to use the [0123456789] character range. [0-9]

The above is the detailed content of Why is `\d` Slower Than `[0-9]` in C# Regex?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn