我想要在示例输入上运行以下正则表达式来替换数字和分数(我需要将它们乘以用户的数字会选择):用分数正则表达式替换分数,用数字正则表达式替换分数
numbersRegex = /[0-9]+(?:\.[0-9]*)?/g;
fractionsRegex = /((\d+)\/(\d+))/g;
的numbersRegex需要对仅包含数字线运行(I标记他们使用numbersRegex下面的示例性输入)。
fractionsRegex需要在包含分数的行上运行(我在下面的示例输入中使用fractionsRegex标记它们)。
我需要它们是两个不同的因为乘法方法不同,所以我想运行str.replace两次,一个乘以所有分数,另一个乘以所有数字。
这里是例如输入:
1 1/2 oz. white rum (fractionsRegex)
1/2 lime, cut in 4 wedges (fractionsRegex)
10 mint leaves, fresh (numbersRegex)
2 tbsp. white sugar (numbersRegex)
1 cup ice cubes (numbersRegex)
1/2 cup club soda (fractionsRegex)
这可能吗?
非常感谢
UPDATE
这是我目前使用(它需要进行清理,我敢肯定,它也可以被优化)功能:
function _increaseServings(target, initialServings, newServings) {
target.html(originalIngredientsHTML);
target.find('li').each(function(i) {
var currentLine = $(this).text();
var importantPart = currentLine.split(',');
var fractionsRegex = importantPart[0].match(/((\d+)\/(\d+))/g);
var lineHiddenFractions = importantPart[0] != null ? importantPart[0].replace(/([0-9]{1,})([\/]{1})([0-9]{1,})/g, "") : "";
var numbersRegex = lineHiddenFractions.match(/([0-9]+(?:\.[0-9]*)?)/g);
var result = {};
var strToReplace = '';
if (fractionsRegex == null && numbersRegex == null) return;
if (fractionsRegex !== null && fractionsRegex.length > 0) {
result.fraction = fractionsRegex[0];
strToReplace = result.fraction;
}
if (numbersRegex !== null && numbersRegex.length > 0) {
result.number = parseInt(numbersRegex[0]);
if(result.fraction) {
strToReplace = result.number + ' ' + strToReplace;
} else {
strToReplace = result.number;
}
}
if(result.fraction) {
var fraction = result.fraction.split('/');
if(result.number && result.fraction) {
result.decimal = parseInt(result.number) + parseInt(fraction[0])/parseInt(fraction[1]);
} else {
result.decimal = parseInt(fraction[0])/parseInt(fraction[1]);
}
} else {
result.decimal = parseInt(result.number);
}
result.stringToReplace = strToReplace;
var newValue = result.decimal * (newServings/initialServings);
if(newValue % 1 != 0) {
var values = String(newValue).split('.');
var checkValue = String(values[1]).slice(0,1);
var integerPart = Math.floor(newValue);
if(checkValue == 2) {
// 25
newValue = integerPart + ' 1/4';
} else if(checkValue == 3) {
// 33
newValue = integerPart + ' 1/3';
} else if(checkValue == 5) {
// 50
newValue = integerPart + ' 1/2';
} else if(checkValue == 6) {
// 66
newValue = integerPart + ' 2/3';
} else if(checkValue == 7) {
// 75
newValue = integerPart + ' 3/4';
}
if(integerPart == 0) newValue = newValue.slice(2, newValue.length);
}
currentLine = currentLine.replace(strToReplace, newValue);
$(this).text(currentLine);
});
}
不知道我是否理解你的问题。你想** 1 **正则表达式,将提取分数线的分数和没有分数的线的数量? – 2012-02-29 18:32:34
我真的不明白你的问题。你想确定字符串是否包含一个小数或一个数字来决定你将使用哪一个正则表达式?如果是这样,首先使用分数正则表达式测试字符串是否包含分数。如果测试失败,请使用数字正则表达式。如果这没有帮助,请澄清你的问题。 :) – tleilax 2012-02-29 18:30:03
我编辑了问题来解释更好 – 2012-02-29 18:48:13