我的输入是
<option value="" disabled selected hidden>
输出应该是这样的:
<option value="" disabled="disabled" selected="selected" hidden="">
然后我尝试了这段代码;
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);
它实际上有效但是因为我被要求做得更简单,我希望我能找到一些非常有用且更简单的东西,因为我试图应用其他方法但它不会工作并试图寻找一些其他方式。
答案 0 :(得分:0)
试试这个:
"<option(.*?)\\s+(disabled)\\s+(selected)\\s+(hidden)>"
JAVA示例
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);