for (j = 0; j < split_compounds_2.length; j++) { //System.out.println(split_compounds_2[j] + "\n"); //regular_expression = "(\\b" + split_compounds_2[j].trim() + "\\b\\W?)"; //(?:\W|^)\Q$term\E(?:(?=\W)|\z) regular_expression = "(?:\\W|^)\\b"+ split_compounds_2[j].trim() + "\\b\\W?(?:(?=\\W?))"; System.out.println(regular_expression + "\n"); new_reaction_2 = new_reaction_2.replaceAll(regular_expression , " [" + compound_id[0] + "] "); }