如何使用正则表达式从字符串中提取特定数字?

How can I extract a certain number from a string using Regular expressions?

我认为这可能很容易,但我没有时间学习如何做。

在一个 html 文件中,我有一个特定的 class 段落,比方说:

<p class="footnote"></p>

"p" 标签后面始终跟有数字,每次加一。假设第一个数字是“43”。我希望数字系列从 1 开始,所以我需要从所有段落中减去 42。

例如,我想从:

<p class="footnote">43. Lorem</p>
<p class="footnote">44. Ipsum</p>. 
<p class="footnote">45. Dolor</p>. 

<p class="footnote">1. Lorem</p>
<p class="footnote">2. Ipsum</p>. 
<p class="footnote">3. Dolor</p>. 

我该怎么做?

使用 javascript 获取文本(尽管我将使用 jQuery),拆分文本,获取第一个元素,然后转换为整数。

$(".footnote").each(function(){
    var text = $(this).text();  // Get text
    var num = text.split(/\s+/g)[0]; // Split by whitespace and get the first elem
    console.log(parseInt(num)); // Convert the elem to an int
});

如果您正在寻找能够处理 <p class="footnote">43. Lorem</p> 的正则表达式,答案是 don't parse HTML with regex

假设您已经从标签中提取了字符串 43. Lorem,并且您想要得到一个数字,那么这取决于您的要求:

要查找任何数字:\d+

求任意数字开头:^\d+

要查找后跟句点的任意数字:\d+\.

更完整的解决方案将需要有关问题的更多详细信息,包括您要使用的编程语言。