javascript - 我怎样才能得到号码和他们的单位?
问题描述
我想在字符串中创建一个正则表达式来“-任意数字+单位”
例如我有这个字符串:
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”
解决方案
匹配连字符和 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]);
}
推荐阅读
- filter - 在地图视图中过滤特征 React-Map-gl React Hooks
- javascript - 具有相似日期的相同时刻语法给出完全不同的结果
- php - 我正在尝试显示文件夹中的多个随机非重复图像,但我得到空白图像
- python - >比较中的ValueError
- python - 使用 Python 绘制已经计算好的混淆矩阵
- python - 如果 B 中存在 A 的 ID,如何使 dataframeA 无
- javascript - javascript 需要 ewelink-api 不起作用?
- android - 颤振“包获取”失败并出现错误“无法读取文件 LocalFile ...”
- phalcon - 在哪里为 phalcon 4 中的自定义过滤器 css 代码创建文件?
- azure - 如何在 Azure DevOps 管道中使用 terraform 输出作为变量