首页 > 解决方案 > 我怎样才能得到号码和他们的单位?

问题描述

我想在字符串中创建一个正则表达式来“-任意数字+单位”

例如我有这个字符串:

hello- world- 86 lo.  => 86 lo


in the -world- 6 lb   => 6 lb



and- the- dog -8kl     => 8kl

let data='in the world- 6 lo'

let  reg =  /-[0-9][a-z]/gi;
let matches = data.match(reg);
console.log(matches)

他的回答是:

let data='in the world- 6 lo'

    let  reg =  /-\s*([0-9]+\s*[a-z]+)/;
    let matches = data.match(reg);
    console.log(matches)

我得到两个答案 [“- 6 lo”、“6 lo”]

我只想得到第二个=>“6 lo”

标签: javascriptregex

解决方案


匹配连字符和 0+ 个空格字符。第1 组中的捕获匹配 1 个以上的数字、可选的空白字符和 1 个或多个字符 az。

带有可选小数部分的特定匹配,添加单位:

-\s*([0-9]+(?:\.\d+)?(?:\s*(?:l[ob]|kl))?)\b

正则表达式演示

const regex = /-\s*([0-9]+(?:\.\d+)?(?:\s*(?:l[ob]|kl))?)\b/g;
const str = `hello- world- 86 lo
in the -world- 6 lb
and- the- dog -8kl
hello- world- 86.6 lo
hello- world- 86`;

while ((m = regex.exec(str)) !== null) {
  console.log(m[1]);
}

或更广泛的匹配:

-\s*([0-9]+(?:\.\d+)?(?:\s*[a-z]+)?)\b

正则表达式演示

const regex = /-\s*([0-9]+(?:\.\d+)?(?:\s*[a-z]+)?)\b/g;
const str = `hello- world- 86 lo
in the -world- 6 lb
and- the- dog -8kl
hello- world- 86.6 lo
hello- world- 86`;
let m;

while ((m = regex.exec(str)) !== null) {
  console.log(m[1]);
}


推荐阅读