Manoj Shrestha
Manoj Shrestha

Reputation: 4684

Using regex, how to change the attribute values from one pattern to another

I have a html file in which the html elements have name as follows :

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

My requirement is to rename the name attribute value in java naming convention as follows :

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

Since there are large number of such elements, I want to accomplish that using regex. Can anyone suggest my how to achieve that using regex ?

Upvotes: 0

Views: 1822

Answers (3)

Pshemo
Pshemo

Reputation: 124215

In most cases using regex with html is bad practice, but if you must use it, then here is one of solutions.

So first you can find text in name="XXX" attribute. It can be done by using this regex (?<=name=")[a-zA-Z_]+(?="). When you find it, replace "_" by "" and don't forget to lowercase rest of letters. Now you can replace old value by new one using same regex we used before.

This should do the trick

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"/>

Upvotes: 1

Hidde
Hidde

Reputation: 11921

Using jQuery to get the name, and then regexes to replace all the _[a-z] occurances:

$('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);
});

Upvotes: 1

npinti
npinti

Reputation: 52185

Do not use regular expressions to go over HTML (why here). Using an appropriate framework such as HTML Parser should do the trick.

A series of samples to get you started are available here.

Upvotes: 1

Related Questions