regex - Java Regular expression with variable string -
i want find occurrences of words in listarray comparing string. far, able loop, store possible combinations , run them using matches i.e.
for(string temp_keywords: keywords){ final_keywords_list.add(" "+ temp_keywords+ " "); final_keywords_list.add(" "+ temp_keywords+"."); final_keywords_list.add(" "+ temp_keywords+ ","); final_keywords_list.add(" "+ temp_keywords+ "!"); final_keywords_list.add(" "+ temp_keywords+ "/"); final_keywords_list.add(" "+ temp_keywords+ "?"); } (string temp_keywords : final_keywords_list) { string add_space = temp_keywords.tolowercase(); p = pattern.compile(add_space); m = p.matcher(handler_string); int count = 0; while (m.find()) { count += 1; } however, want remove manual addition combinations , regex. i've seen examples of words regex how add variable string regex? sorry, beginner java learner.
is need?
string inputstring = .... string[] keywords = .... stringbuilder sb = new stringbuilder(); for(string keyword: keywords) sb.append("(?<= )").append(keyword).append("(?=[ .,!/?])").append("|"); sb.setlength(sb.length() - 1); //removes trailing "|". assumes keywords.size() > 0. pattern p = pattern.compile(sb.tostring()); matcher m = p.matcher(inputstring); int count = 0; while (m.find()) count++; it creates single regex, compiles it, , counts matches.
Comments
Post a Comment