Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match hyphens with Regular Expression?

Tags:

c#

regex

How to rewrite the [a-zA-Z0-9!$* \t\r\n] pattern to match hyphen along with the existing characters ?

like image 841
Thomas Anderson Avatar asked Nov 01 '10 11:11

Thomas Anderson


People also ask

How can you match regular expressions?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .

Do we need to escape hyphen in regex?

You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).

How do you match anything up until this sequence of characters in regular expression?

If you add a * after it – /^[^abc]*/ – the regular expression will continue to add each subsequent character to the result, until it meets either an a , or b , or c . For example, with the source string "qwerty qwerty whatever abc hello" , the expression will match up to "qwerty qwerty wh" .

How do you match a character before regex?

A regular expression to match everything before a specific character makes use of a wildcard character and a capture group to store the matched value. Another method involves using a negated character class combined with an anchor.


1 Answers

The hyphen is usually a normal character in regular expressions. Only if it’s in a character class and between two other characters does it take a special meaning.

Thus:

  • [-] matches a hyphen.
  • [abc-] matches a, b, c or a hyphen.
  • [-abc] matches a, b, c or a hyphen.
  • [ab-d] matches a, b, c or d (only here the hyphen denotes a character range).
like image 126
Konrad Rudolph Avatar answered Sep 22 '22 02:09

Konrad Rudolph