Regular expression (RegEx) search queries are universal and very flexible, but at the same time, in large indexes, their performance can be low, because the regular expression is matched against the words of the index. Another limitation of regular expressions is that search with a pattern is done for each word separately, and not the entire text of a document field. Words are stored in the index in lower case, therefore regular expression search is always case-insensitive.
Queries of this type in text form always start with the caret character, and if the regular expression itself also starts with the caret character, then there will be two caret characters at the beginning of the query.
The following example demonstrates the regex search in text and object forms.
C#
stringindexFolder=@"c:\MyIndex\";stringdocumentsFolder=@"c:\MyDocuments\";// Creating an index in the specified folderIndexindex=newIndex(indexFolder);// Indexing documents from the specified folderindex.Add(documentsFolder);// Search with a regular expression in text formstringquery1="^^(.)\\1{1,}";// The first caret character at the beginning indicates that this is a regular expression search querySearchResultresult1=index.Search(query1);// Search for two or more identical characters at the beginning of a word// Search with a regular expression in object formSearchQueryquery2=SearchQuery.CreateRegexQuery("^(.)\\1{1,}");// Search for two or more identical characters at the beginning of a wordSearchResultresult2=index.Search(query2);
In object form, a regular expression query can also be created with the CreateRegexQuery method overload that takes a combination of RegexOptions values as the second argument. The options must contain the RegexOptions.IgnoreCase flag; otherwise, ArgumentException is thrown. The overload with one argument uses RegexOptions.IgnoreCase.
C#
stringindexFolder=@"c:\MyIndex\";stringdocumentsFolder=@"c:\MyDocuments\";// Creating an index in the specified folderIndexindex=newIndex(indexFolder);// Indexing documents from the specified folderindex.Add(documentsFolder);// Creating a regular expression query with the specified optionsRegexOptionsregexOptions=RegexOptions.IgnoreCase|RegexOptions.CultureInvariant;SearchQueryquery=SearchQuery.CreateRegexQuery("^(.)\\1{1,}",regexOptions);// Search for two or more identical characters at the beginning of a wordSearchResultresult=index.Search(query);
Since version 26.10, regular expression search uses as many threads as there are processor cores by default. Therefore, the order of the found words in the search result may differ from run to run. To get the same order every time, set the SearchThreads index setting to NumberOfThreads.One.
More resources
GitHub examples
You may easily run the code from documentation articles and see the features in action in our GitHub examples: