开发者

Java - regular expression search a string

I am reading a string from a file that reads like

<div style="Z-INDEX: 654; BORDER-BOTTOM: 0px; POSITION: absolute; BORDER-LEFT: 0px; WIDTH: 80px; HEIGHT: 22px; BORDER-TOP: 0px; TOP: 64px; CURSOR: auto; BORDER-RIGHT: 0px; LEFT: 240px" id="textboxElt11286249556014dIi15v" lineid="lineid" pos_rel="fals开发者_运维知识库e" x1="240" x2="320" y1="64" y2="86"><input style="WIDTH: 80px; HEIGHT: 20px" id="textboxElt11286249556014dIi15v_textbox" title="Enter Registration Number Here" tabindex="1" value=" " maxlength="15" size="10" name="scheduled_tribe_registration_number_text"></input></div>

there will be multiple lines of this sort and data is not fixed i want to fetch the value of style i want to do it with regular expressions as the child elements too can have style attributes in them and i want to fetch all style attributes


There are many good html parser libraries for Java, HTMLCleaner is one of them.

Here is a better way to get style attribute:

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

public class Test {

    public static void main(String[] args) throws Throwable {
        HtmlCleaner cleaner = new HtmlCleaner();
        String html = "<div style=\"Z-INDEX: 654; BORDER-BOTTOM: 0px; POSITION: absolute; BORDER-LEFT: 0px; WIDTH: 80px; HEIGHT: 22px; BORDER-TOP: 0px; TOP: 64px; CURSOR: auto; BORDER-RIGHT: 0px; LEFT: 240px\" id=\"textboxElt11286249556014dIi15v\" lineid=\"lineid\" pos_rel=\"false\" x1=\"240\" x2=\"320\" y1=\"64\" y2=\"86\"><input style=\"WIDTH: 80px; HEIGHT: 20px\" id=\"textboxElt11286249556014dIi15v_textbox\" title=\"Enter Registration Number Here\" tabindex=\"1\" value=\" \" maxlength=\"15\" size=\"10\" name=\"scheduled_tribe_registration_number_text\"></input></div>";
        TagNode node = cleaner.clean(html);
        TagNode div = node.findElementByName("div", true);
        System.out.println(div.getAttributeByName("style"));
    }
}

If you are familiar with jquery, you should also check the jsoup.


Don't use regex to parse html. This one uses a regular expression too:

String line = getNextLineFromInput();
String[] parts = line.split("\"");
String style = "";
for (int i = 0; i < parts.length; i++) {
  if (parts[i].endsWith("style=") {
    style = parts[i+1];
    break;
  }
}

Note: this will fail for all real world html files, but you mentioned some input with lines just like your example line; this is a very specialised solution for exactly this type of input.


Don't use regex to parse html. That being said, you can use something like :

<div \s*style="([A-Z0-9-;: ]*)"\s*>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜