From db61e57893373e4d4fcc746a18f9c00ad28ff2a2 Mon Sep 17 00:00:00 2001 From: jeremystretch Date: Fri, 2 Dec 2022 12:54:35 -0500 Subject: [PATCH] Closes #11090: Add regular expression support to global search engine --- docs/release-notes/version-3.4.md | 1 + netbox/netbox/forms/__init__.py | 14 ++++++++++++++ netbox/netbox/search/__init__.py | 1 + 3 files changed, 16 insertions(+) diff --git a/docs/release-notes/version-3.4.md b/docs/release-notes/version-3.4.md index 35f938afd..e3f279169 100644 --- a/docs/release-notes/version-3.4.md +++ b/docs/release-notes/version-3.4.md @@ -5,6 +5,7 @@ ### Enhancements * [#815](https://github.com/netbox-community/netbox/issues/815) - Enable specifying terminations when bulk importing circuits +* [#11090](https://github.com/netbox-community/netbox/issues/11090) - Add regular expression support to global search engine ### Bug Fixes diff --git a/netbox/netbox/forms/__init__.py b/netbox/netbox/forms/__init__.py index fd4998274..d8acef94c 100644 --- a/netbox/netbox/forms/__init__.py +++ b/netbox/netbox/forms/__init__.py @@ -1,3 +1,5 @@ +import re + from django import forms from django.utils.translation import gettext as _ @@ -12,6 +14,7 @@ LOOKUP_CHOICES = ( (LookupTypes.EXACT, _('Exact match')), (LookupTypes.STARTSWITH, _('Starts with')), (LookupTypes.ENDSWITH, _('Ends with')), + (LookupTypes.REGEX, _('Regex')), ) @@ -43,3 +46,14 @@ class SearchForm(BootstrapMixin, forms.Form): super().__init__(*args, **kwargs) self.fields['obj_types'].choices = search_backend.get_object_types() + + def clean(self): + + # Validate regular expressions + if self.cleaned_data['lookup'] == LookupTypes.REGEX: + try: + re.compile(self.cleaned_data['q']) + except re.error as e: + raise forms.ValidationError({ + 'q': f'Invalid regular expression: {e}' + }) diff --git a/netbox/netbox/search/__init__.py b/netbox/netbox/search/__init__.py index 1e856885a..1eec8e097 100644 --- a/netbox/netbox/search/__init__.py +++ b/netbox/netbox/search/__init__.py @@ -18,6 +18,7 @@ class LookupTypes: EXACT = 'iexact' STARTSWITH = 'istartswith' ENDSWITH = 'iendswith' + REGEX = 'iregex' class SearchIndex: