Created
July 21, 2020 11:25
-
-
Save jaredpalmer/8609dc5003400a2e97648cc4bbc8bf03 to your computer and use it in GitHub Desktop.
Search String parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.formium.util; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.StringJoiner; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class SearchUtil { | |
public static Map<String,String> parseSearchQuery(String query) { | |
Pattern p = Pattern.compile("\"[^\"]+\""); | |
Matcher m = p.matcher(query); | |
StringBuffer sb = new StringBuffer(); | |
while (m.find()) { | |
String key = m.group(); | |
m.appendReplacement(sb, key.replace(' ', '_').substring(1, key.length()-1)); | |
} | |
m.appendTail(sb); | |
Map<String,String> results = new HashMap<>(); | |
String[] terms = sb.toString().split(" "); | |
StringJoiner sj = new StringJoiner(" "); | |
for (String term : terms) { | |
if (term.indexOf(':') > -1) { | |
results.put(term.split(":")[0], term.split(":")[1].replace('_', ' ')); | |
} else { | |
sj.add(term); | |
} | |
} | |
String search = sj.toString().trim(); | |
if (!search.isEmpty()) { | |
results.put("", search); | |
} | |
return results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment