Query Rules: RegEx Match Anywhere in Query
I was asked to have a look at an old unanswered question on Stack Exchange: “Can you create a Query Rule that matches in the middle of the query?”. Challenge accepted. I looked at all of the other options and they either match the beginning, the end, or the entire query. This was SharePoint Enterprise. Good thing. SharePoint Online does not support RegEx in Query Rules, but SharePoint Enterprise does.
MVP Andrew Connell loves to ask “If you solve a problem with RegEx, what have you got?” “Two Problems.” I have to agree, I really suck at RegEx. I try not to use it, but when I do I tend to rely very heavily on RegEx testers like RegEx101.com.
I solved this in SharePoint 2013 Enterprise with a Query Rule using Advanced Query Text Match. If my chosen keyword is Ruby create the following rule:
(.*?)(?i:\bruby\b)(.*?)
if you want the keyword anywhere in any string omit the \b word boundary operator like this
(.\*?)(?i:ruby)(.\*?)
I am NOT a RegEx expert (not even close) so there are probably 100 different ways to write this. My understanding is rule matches the case insensitive phrase “ruby” anywhere in the query with zero or more words before or after the keyword. The thing I learned is that since “Entire query matches exactly” is the default, your RegEx has to successfully match all combinations of the query. I tested this with the following combinations of query terms:
It did not hit:
For extra credit, just in case you wanted the option for multiple keywords, I tested
(.\*?)(?i:\bruby\b|\bwilla\b)(.\*?)
and this matches on either “Ruby” or “Willa”. Continue piping additional terms as needed.
For extra extra credit, just in case you wanted to capture the keyword used, you could use
(.\*?)(?<phrase>(?i:\bruby\b|\bwilla\b))(.\*?)
which SharePoint will recognize as a Capture Group and populate the variable {phrase} with the term (in this case “ruby” or “willa”) for use in a Result Block. The Query Variables UI will change to indicate the presence of the capture group. Capture Group in Query Variable
Here is the RegEx: Sample RegEx
There are plenty of good reasons to avoid RegEx. You should consider that there is a performance penalty when the query has to decipher regex. (Which way be why it’s not available in SharePoint Online.) Another, as pointed out by Mikael Svenson, is that advanced queries, like those containing a property query, phrase, or operator, may not match. So you really need to decide what problem you are trying to solve and use the appropriate tool!
Ready to start your next project with us? That’s great! Give us a call or send us an email and we will get back to you as soon as possible!
+1.512.539.0322