开发者

Parsing text with simple wildcards logic in Java / C / Objective-C

I'm looking for a fast library/class to parse plain text using expressions like below:

Text is: <b>Name:</b>John<br><i>Age</i>32<br>

Pattern is: {*}Name:</b>{%}<br>{*}Age</i>{%}<br>

And it will find me two values: John and 32. Intent is to parse simple HTML web pages without involving heavy duty tools. It should not be using string operation开发者_运维技巧s or regexps internally but probably do char by char parsing.


Since you appear to be asking the user to specify the HTML content you want, it's probably alright to use regular expressions here (why do you have an aversion to them?). It's not HTML parsing, anymore, just simple text matching, which is what regular expressions are designed for.

Here's an example:

$match =~ s/{\*}/.*?/g;
$match =~ s/{%}/(.*?)/g;
$html =~ /$match/;

Which will leave what you need in your capturing groups.


A regex replacement would work. Just get it to return both values together like "John%32" and then split the response to get the two separate values.


There's really no advantage to character-by-character parsing manually implemented here, as such problems have been by and large solved for these types of problems.

  • If you're dealing with an extremely normalized set of data (i.e. the template you described above is formatted exactly the same in every circumstance with no possibility of missing closing tags, HTML being inserted in odd places, etc.), regular expressions are a perfectly appropriate tool to parse this sort of data.
  • If the HTML can not be guaranteed to be perfect, then the most straightforward solution is to use a tool to load the HTML structure into a DOM and find the appropriate elements in the document tree.

Developing a character-by-character approach will probably end up being equivalent to manually implementing one of the above two options, which is not a trivial thing to implement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜