Skip to content

feat: add matches_regex filter and string_matching_regex expression test - #1332

Open
craigayre wants to merge 1 commit into
HubSpot:masterfrom
craigayre:add-matches-regex
Open

feat: add matches_regex filter and string_matching_regex expression test#1332
craigayre wants to merge 1 commit into
HubSpot:masterfrom
craigayre:add-matches-regex

Conversation

@craigayre

Copy link
Copy Markdown

Description

There's no direct way to test whether a string matches a regex. We've been working around it with things like:

{% if var and var|regex_replace('^pattern$', '') == '' %}

This adds a matches_regex filter and a string_matching_regex expression test so you can write:

{{ 'hello'|matches_regex('^[a-z]+$') }}
{% if var is string_matching_regex '[0-9]+' %}
{{ items|selectattr('name', 'string_matching_regex', '^foo') }}

Both use RE2 (com.google.re2j) consistent with the existing regex_replace filter. Both use partial matching (Matcher.find), anchor with ^...$ for full-string matching.

Testing

  • MatchesRegexFilterTest (9 tests): matching/non-matching, anchored patterns, null input, null arg, missing arg, invalid regex, SafeString, and maxStringLength enforcement.
  • IsStringMatchingRegexExpTestTest (5 tests): matching/non-matching, null arg, SafeString, and end-to-end selectattr filtering.

Notes

  • Happy to change the naming (matches_regex / string_matching_regex) if there's something more appropriate.
  • The implementations are based on the existing string_containing expression test and regex_replace filter. There could probably be some simplifications, but kept things consistent with the existing implementations intentionally.

🤖 Claude Code assisted.

There's no direct way to test whether a string matches a regex. We've
been working around it with things like:

  {% if var and var|regex_replace('^pattern$', '') == '' %}

This adds a matches_regex filter and a string_matching_regex expression
test so you can write:

  {{ 'hello'|matches_regex('^[a-z]+$') }}
  {% if var is string_matching_regex '[0-9]+' %}
  {{ items|selectattr('name', 'string_matching_regex', '^foo') }}

Both use RE2 (com.google.re2j) consistent with the existing
regex_replace filter. Both use partial matching (Matcher.find), anchor
with ^...$ for full-string matching.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant