Regex
<b>(\\S+)</b>
Giải thích
<b>- thẻ mở bold(\\S+)- group 1: một hoặc nhiều non-whitespace</b>- thẻ đóng bold
Ví dụ
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
String str = "This is an example>/b> HTML script.
";
String regex = "(\\S+)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Kết quả
<b>is</b>
<b>example</b>
<b>script</b>
Lưu ý quan trọng
- Regex này không xử lý HTML lồng nhau hoặc attribute.
- Thực tế parse HTML nên dùng Jsoup, không dùng regex.
- Ví dụ có lỗi:
example>/bthiếu<nhưng regex vẫn khớp do\\S+.
Cải tiến
// Lấy chỉ nội dung (group 1)
while (matcher.find()) {
System.out.println(matcher.group(1)); // is, example, script
}
// Cho phép attribute: content
String regex = "]*>([^<]+)";