Escape a hyphen in a regular expression

When a hyphen needs escaping in a regex, when placing it first or last is safer, and how string literals, JavaScript flags, POSIX tools and copy-paste can break the pattern.

Short answer

A hyphen only has special meaning inside a character class, where it forms a range such as [a-z]. Outside a class it is an ordinary character and needs no escape. Inside a class you can make it literal in two ways: escape it as - in flavors that support backslash escapes in classes, or place it first or last in the class. Placement is the more portable choice and avoids extra backslashes when the pattern is embedded in source code or data files. Escaping is clearer to some readers, but it fails or behaves differently in a few environments described below.

Is escaping the right choice for your pattern?

Escaping with a backslash suits patterns that stay within one backslash-escape engine, such as PCRE, Python, Java, .NET or JavaScript, and that are maintained by people who expect every literal to be marked explicitly. Its main benefit is that the hyphen can sit anywhere in the class without being misread as a range. The decisive tradeoff is that the backslash must survive every layer the pattern passes through, and it is not interpreted as an escape in POSIX bracket expressions. Placing the hyphen first or last, as in [-.\w] or [\w.-], is usually preferable when the pattern is shared across tools, stored in JSON or configuration files, or used with grep, sed or other POSIX utilities.

  • Escape with - when: the pattern targets one backslash-escape engine and the hyphen must appear mid-class for readability.
  • Place it first or last when: the pattern must work in POSIX tools, across several engines, or inside string literals where each backslash has to be doubled.
  • Use no escape at all when: the hyphen is outside any character class, such as in a phone-number pattern like \d{3}-\d{4}.

What escaping actually changes

Escaping does not change the text being searched. It changes how the regex engine parses the pattern: the backslash tells the parser to treat the following hyphen as a literal member of the class rather than as a range operator. The examples below show how position and escaping affect meaning.

[a-z]    range: any lowercase letter from a through z
[az-]    literal: a, z or hyphen
[-az]    literal: hyphen, a or z
[^-az]   negated: any character except hyphen, a or z
[a\-z]   literal: a, hyphen or z (backslash-escape flavors)
a-z      outside a class: the characters a, -, z in sequence

The word "escape" is used for two separate layers, and confusing them is the most common source of broken patterns. Regex escaping is what the engine sees, such as -. String-literal escaping is what a programming language or data format requires to deliver that backslash to the engine. A pattern that is correct at the regex layer can still arrive wrong if the string layer consumes or rejects its backslash.

Engine differences that affect the hyphen

In PCRE, Python, Java and .NET, an escaped hyphen is accepted both inside and outside a class, so an unnecessary - outside a class is harmless there. JavaScript is stricter when the u or v flag is set. In Unicode mode, the specification only permits - inside a character class, and the v flag goes further by reserving the bare hyphen inside classes for ranges and set operations.

/\-/      matches a hyphen (legacy identity escape, no flag)
/\-/u     SyntaxError: \- is not a valid escape outside a class in Unicode mode
/[\-]/u   matches a hyphen
/[\-]/v   matches a hyphen
/[-]/v    SyntaxError: a literal hyphen must be escaped in v-mode classes

POSIX bracket expressions, used by tools such as grep and sed, specify that a backslash loses its special meaning inside brackets. There, [a-z] is not an escaped hyphen; it can be read as a range or as including a literal backslash, depending on the surrounding characters. For POSIX tools, put the hyphen first or last. Some tools, including certain awk implementations, treat backslashes in brackets differently, so check the documentation for the specific tool rather than assuming one behavior.

.NET also supports character class subtraction, written as [a-z-[aeiou]]. A hyphen placed immediately before an opening bracket inside a class triggers subtraction, so avoid that position when a literal hyphen is intended.

Will the pattern survive copying into code or sharing?

The same regex must be written differently depending on where it is stored. Each backslash in the pattern may need to be doubled when the host language or format also uses backslash escapes. The examples below represent one pattern that matches word characters, dots and hyphens.

Regex as the engine sees it:  [\w\-.]+
JavaScript regex literal:     /[\w\-.]+/
JavaScript string:            new RegExp("[\\w\\-.]+")
Python raw string:            re.compile(r"[\w\-.]+")
Java string:                  Pattern.compile("[\\w\\-.]+")
C# verbatim string:           new Regex(@"[\w\-.]+")
JSON string value:            "[\\w\\-.]+"

Writing the same pattern as [\w.-]+ removes one escape at every layer, which is why placement often reads better once the pattern is embedded. In Python, writing "[-]" in a normal (non-raw) string happens to work because Python keeps unrecognized escapes, but recent versions emit a warning for invalid escape sequences, so a raw string is the safer habit.

Copying patterns through word processors, chat apps or documentation editors carries a separate risk: automatic formatting can replace the ASCII hyphen-minus (U+002D) with a visually similar character such as an en dash (U+2013), a minus sign (U+2212) or a non-breaking hyphen (U+2011). The pattern still looks correct but no longer matches ordinary hyphens, and a replaced hyphen inside a class may stop forming a range. Sharing patterns inside code blocks or plain-text files reduces this risk. If a copied pattern fails unexpectedly, inspect the code point of each dash-like character.

For readability and accessibility, dense escape sequences are hard to read aloud and easy to mistype. Screen readers may announce backslashes and brackets inconsistently depending on settings; no specific assistive technology was tested for this article. When a pattern is published for people to read, presenting it in a code block alongside a plain-language description, such as "letters, digits, underscores, dots or hyphens," gives readers an equivalent that does not depend on parsing the symbols.

Quick reference

Context | Hyphen outside a class | Literal hyphen inside a class
PCRE, Python, Java, .NET | No escape needed; - also accepted | - anywhere, or first or last
JavaScript, no flag | No escape needed; - accepted | - anywhere, or first or last
JavaScript, u flag | No escape; - is a SyntaxError | - anywhere, or first or last
JavaScript, v flag | No escape needed | Must be escaped as -
POSIX grep and sed | No escape needed | First or last only; backslash is not an escape in brackets

Evidence and gaps

The behavior described here reflects the documented rules of the named regex flavors and the POSIX and ECMAScript specifications. No engine versions were tested for this article, and individual tools, older runtimes or library wrappers may differ. Before relying on a pattern in production, run it against a small set of known inputs, including a hyphen, the range endpoints and a lookalike dash, in the exact engine and string context where it will be used.