I am trying to group a string expression into three parts using Regex. It works for most cases and getting stuck for one case.
Regex
([\\w.]+?)(:|<|>|<=|>=|%|-|\\(\\))([\\w\\s,.:-]+?)\\|
Code:
private SearchCriteria validateFilterPattern(String filter) {
final Pattern pattern = Pattern.compile("([\\w.]+?)(:|<|>|<=|>=|%|-|\\(\\))([\\w\\s,.:-]+?)\\|");
Matcher m = pattern.matcher(filter + "|");
if (m.find()) {
return SearchCriteria.builder().key(m.group(1)).operator(m.group(2)).value(m.group(3)).build();
} else {
throw new RuntimeException(ErrorMessage.FILTER_FORMAT_INVALID, filter);
}
}
Input is having pattern key:value. The above code is using the regex and grouping the input expression into three parts: key,operator and value. Operators can be: , >, <, >=, <=, *, ~, (), % Keys can be any word, value can contain word, letters, dots, colon,some special characters and brackets.
I am able to match following and group it into three parts.
regulatory:Section 740.17 Mass Market
regulatory:Section 740.17
The above two inputs segregate into groups like
key {regulatory} , operator {:} , value {Section 740.17 Mass Market}
key {regulatory} , operator {:} , value {Section 740.17}
But not able to group it for inputs where value contains brackets.
regulatory:Section 740.17(b)(1) Mass Market
regulatory()Section 740.17(b)(1) Mass Market
The above should segregate into groups like
key {regulatory} , operator {:} , value {Section 740.17(b)(1) Mass Market}
key {regulatory} , operator {()} , value {Section 740.17(b)(1) Mass Market}
Able to solve it by using below regex
"([\\w.]+?)(:|<|>|<=|>=|%|-|\\(\\))([\\w\\s,.:\\(\\)-]+?)\\|"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.