正则表达式仅匹配来自 HTML table 的第一个结果或第二个结果
Regex match just first result or second from HTML table
我正在使用正则表达式应用内脚本 javascript。我尝试从每个 table 中获取第一个值或第二个值,但没有用。
<table>
<td class="bar">
<td class="center">hello1</td>
<td class="center">hello2</td>
<td class="center">hello3</td>
</td>
</table>
<table>
<td class="bar">
<td class="center">hello1</td>
<td class="center">hello2</td>
<td class="center">hello3</td>
</td>
</table>
我的代码正则表达式:/(?<=<td class=\"center\">).*?(?=<\/td>)/gi
此代码 selects 所有值 您好。我只想要来自第一个 table td 和第二个 table td 的 select Hello1。
我删除了全局但只给我第一个 table.
中的第一个 td
hello 值是动态的,不固定。
您可以做一些正则表达式 like this 来检索您期望的文本...
通过在标签中排除 <>
个字符来基本匹配标签。
不过,我认为在 JavaScript 和 DOM 中执行此操作的更简单且不易出错的方法是使用 querySelectorAll
,例如...
let c = document.querySelectorAll('td:nth-of-type(2)');
console.log(Array.from(c).map(i => i.innerText));
<table>
<td class="bar">
<td class="center">hello1</td>
<td class="center">hello2</td>
<td class="center">hello3</td>
</td>
</table>
<table>
<td class="bar">
<td class="center">hello1</td>
<td class="center">hello2</td>
<td class="center">hello3</td>
</td>
</table>
我正在使用正则表达式应用内脚本 javascript。我尝试从每个 table 中获取第一个值或第二个值,但没有用。
<table>
<td class="bar">
<td class="center">hello1</td>
<td class="center">hello2</td>
<td class="center">hello3</td>
</td>
</table>
<table>
<td class="bar">
<td class="center">hello1</td>
<td class="center">hello2</td>
<td class="center">hello3</td>
</td>
</table>
我的代码正则表达式:/(?<=<td class=\"center\">).*?(?=<\/td>)/gi
此代码 selects 所有值 您好。我只想要来自第一个 table td 和第二个 table td 的 select Hello1。 我删除了全局但只给我第一个 table.
中的第一个 tdhello 值是动态的,不固定。
您可以做一些正则表达式 like this 来检索您期望的文本...
通过在标签中排除 <>
个字符来基本匹配标签。
不过,我认为在 JavaScript 和 DOM 中执行此操作的更简单且不易出错的方法是使用 querySelectorAll
,例如...
let c = document.querySelectorAll('td:nth-of-type(2)');
console.log(Array.from(c).map(i => i.innerText));
<table>
<td class="bar">
<td class="center">hello1</td>
<td class="center">hello2</td>
<td class="center">hello3</td>
</td>
</table>
<table>
<td class="bar">
<td class="center">hello1</td>
<td class="center">hello2</td>
<td class="center">hello3</td>
</td>
</table>