1

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.

  • It seems that you intend to make "syntactically" correct changes to XML data. Hint: then use tools that understand XML. XML and regex is per se not a good mix. As the later **can not at all** cover all the zillion options that correct XML might use. See http://stackoverflow.com/questions/8577060/why-is-it-such-a-bad-idea-to-parse-xml-with-regex for example – GhostCat Oct 26 '16 at 09:40

1 Answers1

0

Try this:

"<option(.*?)\\s+(disabled)\\s+(selected)\\s+(hidden)>"

Explanation

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);
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43