Регулярное выражение для получения атрибута от HTML-тэга

jQuery("#checker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = true;
    });
});
jQuery("#dechecker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = false;
    });
});
jQuery("#checktoggler").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = !this.checked;
    });
});

;)

14
задан Mnementh 3 July 2009 в 13:46
поделиться

3 ответа

One possibility:

String imgRegex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";

is a possibility (if matched case-insensitively). It's a bit of a mess, and deliberately ignores the case where quotes aren't used. To represent it without worrying about string escapes:

<img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>

This matches:

  • one or more characters that aren't > (i.e. possible other attributes)
  • src
  • optional whitespace
  • =
  • optional whitespace
  • starting delimiter of ' or "
  • image source (which may not include a single or double quote)
  • ending delimiter
  • although the expression can stop here, I then added:
    • zero or more characters that are not > (more possible attributes)
    • > to close the tag

Things to note:

  • If you want to include the src= as well, move the open bracket further left :-)
  • This does not care about delimiter balancing or attribute values without delimiters, and it can also choke on badly-formed attributes (such as attributes that include > or image sources that include ' or ").
  • Parsing HTML with regular expressions like this is non-trivial, and at best a quick hack that works in the majority of cases.
24
ответ дан 1 December 2019 в 06:48
поделиться

Здесь часто возникает этот вопрос

Регулярные выражения - плохой способ решения этой проблемы. Сделайте себе одолжение и воспользуйтесь каким-нибудь парсером HTML.

Регулярные выражения плохо подходят для синтаксического анализа HTML. Вы получите сложное выражение, которое будет вести себя неожиданно в некоторых угловых случаях, что будет в противном случае.

Изменить: Если ваш HTML такой простой, то:

Pattern p = Pattern.compile("src\\s*=\\s*([\\"'])?([^ \\"']*)");
Matcher m = p.matcher(str);
if (m.find()) {
  String src = m.group(2);
}

И существует любое количество парсеров Java HTML .

17
ответ дан 1 December 2019 в 06:48
поделиться

You mean the src-attribute of the img-Tag? In that case you can go with the following:

<[Ii][Mm][Gg]\\s*([Ss][Rr][Cc]\\s*=\\s*[\"'].*?[\"'])

That should work. The expression src='...' is in parantheses, so it is a matcher-group and can be processed separately.

0
ответ дан 1 December 2019 в 06:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: