使用正则表达式,如何将属性值从一种模式更改为另一种模式

时间:2012-05-29 09:35:45

标签: java regex

我有一个html文件,其中html元素的名称如下:

<input type="text" name="HCFA_DETAIL_SUPPLEMENTAL" value="" size="64" />

我的要求是在java命名约定中重命名name属性值,如下所示:

<input type="text" name="hcfaDetailSupplemental" value="" size="64" />

由于存在大量此类元素,我想使用正则表达式来实现这一点。任何人都可以建议我如何使用正则表达式实现这一目标吗?

3 个答案:

答案 0 :(得分:1)

不要使用正则表达式来覆盖HTML(为什么here)。使用HTML Parser之类的适当框架应该可以解决问题。

可以使用一系列示例来启动here

答案 1 :(得分:1)

使用jQuery获取名称,然后使用regexes替换所有_[a-z]次出现:

$('input').each(function () {
    var s = $(this).attr('name').toLowerCase();
    while (s.match("_[a-z]"))
        s = s.replace(new RegExp("_[a-z]"), s.match("_[a-z]").toString().toUpperCase());
    $(this).attr('name', s);
});

答案 2 :(得分:1)

在大多数情况下,使用带有html的正则表达式是不好的做法,但如果你必须使用它,那么这是解决方案之一。

首先,您可以在name =“XXX”属性中找到文本。可以使用此正则表达式(?<=name=")[a-zA-Z_]+(?=")来完成。当你找到它时,将“_”替换为“”并且不要忘记小写其余的字母。现在,您可以使用我们之前使用的相同正则表达式替换旧值。

这应该可以解决问题

String html="<input type=\"text\" name=\"HCFA_DETAIL_SUPPLEMENTAL\" value=\"\" size=\"64\"/>";

String reg="(?<=name=\")[a-zA-Z_]+(?=\")";
Pattern pattern=Pattern.compile(reg);
Matcher matcher=pattern.matcher(html);
if (matcher.find()){
    String newName=matcher.group(0);
    //System.out.println(newName);
    newName=newName.toLowerCase().replaceAll("_", "");
    //System.out.println(newName);
    html=html.replaceFirst(reg, newName);
}
System.out.println(html);
//out -> <input type="text" name="hcfadetailsupplemental" value="" size="64"/>