CloudFormation supports regular expressions only in **specific validation contexts** — most commonly the `AllowedPattern` property on a Parameter. The non-obvious gotchas:
## 1. It's Java regex, not PCRE/POSIX
All CFN regexes follow `java.util.regex.Pattern` syntax. This affects:
- Lookbehind features (Java supports finite-width lookbehind only)
- Named group syntax (`(?<name>...)` works; PCRE's `(?P<name>...)` does not)
- Possessive quantifiers (`*+`, `++`, `?+`) — Java has them, ICU/POSIX does not
When porting regexes from other tools, validate against the Java spec, not just "does it look right."
## 2. JSON requires double-escaped backslashes
JSON itself reserves `\` as an escape character, so any backslash in your regex must be written twice. Example — match four digits:
**JSON** (`\\d` survives JSON parsing as `\d`):
```json
{
"Parameters": {
"MyParameter": {
"Type": "String",
"AllowedPattern": "\\d{4}"
}
}
}
```
**YAML** (single quotes prevent backslash interpretation):
```yaml
Parameters:
MyParameter:
Type: String
AllowedPattern: '\d{4}'
```
The YAML form is unambiguously cleaner. Forgetting to single-quote in YAML is a common silent failure — the regex still parses but matches the wrong thing.
## 3. `Fn::Equals` is NOT a regex match
This is the surprise: `Fn::Equals` and the other comparison intrinsics perform **exact string comparison only**. There is no `Fn::Matches` or regex-aware comparison anywhere in the intrinsic function library.
If you need pattern-driven branching in `Conditions`, your only options are:
- Pre-validate via `AllowedPattern` on the Parameter (rejects invalid input at stack-create time)
- Push the logic into a custom resource (Lambda) or a Transform macro
- Use SSM Parameter Store + `AWS::SSM::Parameter::Value<...>` for richer validation
## Where regex actually works
- `Parameters[*].AllowedPattern`
- `Rules` section (assertion expressions on parameter values)
- That's effectively it for top-level template syntax. Resource-level properties may accept patterns where individual AWS services define them, but those are service-specific, not CFN-level.
## Related
- [[CFN Template Structure Nine Sections]]
- [[CFN Template Format JSON vs YAML]]