I've been trying to figure out a regex for Gmail-like search, i.e.:
name:Joe surname:(Foo Bar)
...like in this topic. But with a slight difference: if there is a text without a key:
, it's also split, so:
foo:(hello world) bar:(-{bad things}) some text to search
would return:
foo:(hello world)
bar:(-{bad things})
some text to search
There's no way to grab everything you need using a single regex. The problem is that there is not a reliable way of grabbing the non-keyworded text.
However, if we first grab and store all the keyworded text, then do a regex replace (using the same regular expression) with an empty string, we suddenly get the search string by itself!
Grab the keywords and related text using the following regex (see it on RegExr):
([a-zA-Z]+:(?:\([^)]+?\)|[^( ]+))
Then do a regex replace, with the same regex, on the full search string using an empty string. The resulting string will be the non-keyworded search text. Something along the lines of:
Regex.Replace(searchtext, @"[a-zA-Z]+:(?:\([^)]+?\)|[^( ]+)", "");
Perform whitespace trimming at start and end of the search text
Remove double (or more spaces) from search text (can be done with regex replace, replacing with a single space):
Regex.Replace(searchtext, @" {2,}", " "); ^-- notice the space :)
????
PROFIT!!!
It is entirely possible to perform whitespace removal in the regex in #2, but when dealing with regexes, I tend to prefer keeping it as clean as possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With