1

So I am trying to make a pattern matcher that would read a block of html and identify the labels and ids of certain fields on the page. I am trying to find a way to read the label tag and parse through any spans within it. Currently what I have is this:

labelsToField = new Map<String, String>();
Matcher m = Pattern.compile('<label for="(.*?)">(<span class="\\w+"?>\\*</span>)*(.*?)</label>').matcher(testHtml);
while(m.find()){
    labelsToField.put(m.group(3), m.group(1));
}  

My test cases that I am working on are:

'<label for="00No0000001b7B1">Field1</label>'
'<label for="CF00No0000001b7AG"><span class="assistiveText">*</span>Field2</label>'
'<label for="CF00No0000001b7AM"><span class="requiredMark">*</span><span class="assistiveText">*</span>Field3</label>'
'<label for="Name"><span class="requiredMark">*</span>Field4</label>'
'<label for="00No0000001b7Ay"><span class="requiredMark" class="bar">*</span>Field5</label>'

What the code above should do is parse through these lines and group the text just after the for attribute in label (Name, CFblahblah, etc) with the text that comes just before the closing label (Field1, Field2, etc).

Currently all tests are passing EXCEPT for the last one which is a span tag that has a class and a foo attribute being set.

1
  • WHY would you do this to yourself? This seems like a misguided test. Unit tests are not the most appropriate tool for verifying front end behavior. You should instead rely on functional testing.
    – Adrian Larson
    Commented May 11, 2015 at 18:07

1 Answer 1

1

Honestly, you shouldn't be trying to parse HTML yourself. Just load up a Document, then recursively walk through the XmlNode elements, grabbing whatever attributes/text you want. This avoids an entire class of problems associated with using patterns (complexity limits, etc) when all you want is straightforward access to a fragment of XML-style data.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .