如果 HTML 在字符串中:
$source = '<div class="usernameHolder">Username: user123</div>';
# Allow optional whitespace before or after the username value.
$text = $source=~ /Username:\s*(.*?)\s*</;
print $1 . "\n"; # user123
如果 HTML 在数组中:
@source = (
'<p>Some text</p>',
'<div class="usernameHolder">Username: user123</div>',
'<p>More text</p>'
);
# Combine the matching array elements into a string.
$matching_lines = join "",grep(/Username:\s*(.*?)\s*</, @source);
# Extract the username value.
$text = $matching_lines =~ /Username:\s*(.*?)\s*</;
print $1 . "\n"; # user123
使用数组的更紧凑的版本:
@source = (
'<p>Some text</p>',
'<div class="usernameHolder">Username: user123</div>',
'<p>More text</p>'
);
# Combine the matching array elements in a string, and extract the username value.
$text = (join "",grep(/Username:\s*(.*?)\s*</, @source)) =~ /Username:\s*(.*?)\s*</;
print $1 . "\n"; # user123