用于从段落中提取最后一个数字组合的正则表达式

RegEx for extracting the last combination of numbers from a paragraph

用于从段落中提取最后一个数字组合的正则表达式

例如:

“My ID is 112243 and my phone number is 0987654321. Thanks you.”

所以我想在这里提取 phone 数字,这是最后一个数字组合。

你可以使用这个正则表达式,

\d+(?=\D*$)

这里,\d+ 选择一个或多个数字,这个正向前瞻 (?=\D*$) 确保如果在字符串结尾之前更远的地方存在任何东西,那么它不是数字(通过使用 \D*$ 之前)。

Regex Demo

JS代码演示,

const s = 'My ID is 112243 and my phone number is 0987654321. Thanks you.'

console.log(s.match(/\d+(?=\D*$)/))

var string = "My ID is 112243 and my phone number is 0987654321. Thanks you";
var numbers = string.match(/\d+/g).map(Number);
console.log(numbers);

它会给你一个数组中的所有数字组合。你可以选择你想要的。

您也可以使用简单的正则表达式,例如 ^.*\b(\d+)

var str = 'My ID is 112243 and my phone number is 0987654321. Thanks you';
var num = str.match(/^.*\b(\d+)/)[1];
console.log(num);

  • Greedy .* 将消耗最后 \b 字边界 后跟 \d+ 数字之前的任何内容。
  • \d+ 两边的括号将 capture 里面的东西变成 [1]
  • 如果输入是多行字符串,使用 [\s\S]* instead of .* 跳过换行符。