Reputation:
I have several HTML files, each has a single <h1>
tag in it. I want to parse that tag to get it's content (a name of a book). A tag looks like this for example:
<H1>bookname</H1>
I am trying to get it using this code:
Scanner scan = new Scanner(file, "Windows-1255");
String name="";
Pattern p = Pattern.compile("<H1>*</H1>"); //tried adding '(' and ')' around the '*', didn't help
while (scan.hasNext()) {
name = scan.nextLine();
Matcher m = p.matcher(name);
if (m.matches()) {
name = name.substring(4, name.length() - 6);
break;
}
}
It doesn't work, the h1 tag is never matched and I don't get the name. How is this supposed to be done?
Perhaps it's important, the contents of the H1 tags are in Hebrew, charset=Windows-1255.
Upvotes: 0
Views: 2987
Reputation: 3955
I found an example that might work for you. It simplifies and generalizes also the matching procedure so you don't need to substring your found pattern:
String stringToSearch = "<h1>Yada yada yada yada </h1>";
String name = "";
// the pattern we want to search for
Pattern p = Pattern.compile("<h1>.*</h1>");
Matcher m = p.matcher(stringToSearch);
// if we find a match, get the group
if (m.find())
{
// get the matching group
name = m.group(1);
}
Upvotes: 2
Reputation: 7194
Try using
Pattern p = Pattern.compile("<H1>.*</H1>");
(notice the extra .
- your version matches just empty tags).
Upvotes: 2