【发布时间】:2026-01-09 22:25:01
【问题描述】:
Q) 我希望能够在 js 中解析一个字符串并输出字符串中的数字或分数部分。
例如:"1.5 litres 1/4 cup"
注意:我已经知道如何从下面的示例字符串中获取整数和小数,但不是分数表示。
我目前正在使用这样的东西:
const originalString = "1.5 litres 1/4 cup";
var number_regex = /[+-]?\d+(\.\d+)?/g;
var matches = [];
var match;
// FIX - does this ever actually get stuck ?
// replace this with non-while loop from article: http://danburzo.ro/string-extract/
while ((match = number_regex.exec(originalString)) !== null) {
matches.push({
original: match[0],
newVal: ''
});
}
console.log(matches)
【问题讨论】:
-
请重新打开这个 - 我已经添加了我当前的代码 - 不要这么快判断。
-
你的正则表达式从来没有尝试匹配正斜杠......你应该尝试一些东西,至少......看起来你没有做任何事情来进行额外的匹配,然后离开由我们决定。 downvote 按钮有一个关于此的工具提示...
-
将
\.更改为[.\/]。
标签: javascript regex string typescript fractions