firecatcher firecatcher - 1 year ago 77
Java Question

How to add text in between a sentence using regex?

My input is

<option value="" disabled selected hidden>

The output should be something like this:

<option value="" disabled="disabled" selected="selected" hidden="">

Then I tried this code;

final String REGEX_DISABLED = "(?<=option value=\"\" disabled)(?=.*)";
final String REPLACE_DISABLED = "=\"disabled\"";
Pattern disP = Pattern.compile(REGEX_DISABLED);
Matcher disM = disP.matcher(text);
text = disM.replaceAll(REPLACE_DISABLED);

final String REGEX_SELECTED = "(?<==\"disabled\" selected)(?=.*)";
final String REPLACE_SELECTED = "=\"selected\"";
Pattern selP = Pattern.compile(REGEX_SELECTED);
Matcher selM = selP.matcher(text);
text = selM.replaceAll(REPLACE_SELECTED);

final String REGEX_HIDDEN = "(?<==\"selected\" hidden)(?=.*)";
final String REPLACE_HIDDEN = "=“”";
Pattern hidP = Pattern.compile(REGEX_HIDDEN);
Matcher hidM = hidP.matcher(text);
text = hidM.replaceAll(REPLACE_HIDDEN);

It actually worked but since I was asked to do it more simple, I was hoping if I could find something really useful and more simple since I tried to apply other ways but it won't work and tried searching for some other ways.

Answer Source

Try this:



JAVA Sample

final String regex = "<option(.*?)\\s+(disabled)\\s+(selected)\\s+(hidden)>";
final String string = "<option value=\"\" disabled selected hidden>\n\n"
     + "<option value=\"adfsa\" disabled selected hidden>\n\n"
     + "<option value=\"111\" disabled selected hidden>\n\n\n\n";
final String subst = "<option $1 $2=\"disabled\" $3=\"disabled\" $4=\"hidden\">";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download