正则匹配带text-right类HTML表格单元格内的数字(含点/逗号)
Regex to Extract Numeric Value from the First
.text-right TD Element Since you've confirmed regex is the only feasible approach here despite the usual caveats about parsing HTML with regex, here's a refined solution to target the first <td> with the text-right class and extract its numeric content (supports decimals, comma separators, and handles whitespace/newlines):
Final Regex
(?:<td\b[^>]*?text-right\b[^>]*>)\s*([\d.,]+)\s*(?=<\/td>)
Regex Breakdown
Let's break down how this works to match your requirements:
(?:<td\b[^>]*?text-right\b[^>]*>): Non-capturing group to locate the first<td>tag containing thetext-rightclass.[^>]*ensures we don't stray into other tags, while\bavoids partial class name matches.\s*: Matches any leading whitespace or newlines inside the TD before the numeric value.([\d.,]+): Capturing group that extracts the number—supports digits, dots (decimal points), and commas (thousand separators).\s*: Matches any trailing whitespace or newlines after the number.(?=<\/td>): Positive lookahead to stop exactly before the closing</td>tag.
Example Test
For your sample TD code:
<td class="text-right" onmouseenter="$(this).find('.overlay-viewable-box:first').show();" onmouseleave="$(this).find('.overlay-viewable-box:first').hide();"> 2.004 </td>
This regex will capture the value 2.004 correctly, ignoring the surrounding whitespace and the TD's attributes.
Edge Case Handling
- Works with numbers using commas as decimal separators (e.g.,
1,500or2,34) - Ignores any leading/trailing whitespace or line breaks inside the TD
- Targets only the first
<td>with thetext-rightclass as requested
内容的提问来源于stack exchange,提问作者Evgeniy
相关产品推荐
相关产品推荐

