"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I Use Hyphens Correctly in Regular Expression Character Classes?

How can I Use Hyphens Correctly in Regular Expression Character Classes?

Posted on 2025-02-23
Browse:304

How can I Use Hyphens Correctly in Regular Expression Character Classes?

Hypershadow in regular expression

When using regular expressions, be sure to consider the behavior of various characters in it. In this case, let's explore how to deal with hyphens.

question:

How to modify existing pattern [a-zA-Z0-9!$*\t\r\n] to include hyphen matches?

Answer:

Understand the hyphen in regular expressions

]

Usually, hyphen acts as a normal character in a regular expression. However, their behavior changes slightly when they appear in the character class [] and have other characters before and after them. In these specific cases, they have special uses.

Match hyphen

]

To match hyphen, you can choose the following options:

  • directly use hyphen: The hyphen in the character class - represents itself.
  • Escape hyphen: You can also use \- to escape hyphen, although this is not required.

Example

Consider the following scenarios:

  • [-abc]: Match any instance of the characters a, b, c, or hyphen.
  • [-abc]: equivalent to [-abc].
  • [ab\-c]: Match a, b, c or hyphen. Pay attention to the position of escape hyphen.
  • [ab-d]: Specifies the range from a to d, excluding hyphens. Here the hyphen is interpreted as a range indicator.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3