如何使用正则表达式在句子之间添加文本?

时间:2016-10-26 09:38:11

标签: java regex string

我的输入是

<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);

它实际上有效但是因为我被要求做得更简单,我希望我能找到一些非常有用且更简单的东西,因为我试图应用其他方法但它不会工作并试图寻找一些其他方式。

1 个答案:

答案 0 :(得分:0)

试试这个:

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

Explanation

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);