2017-03-13 10 views
1

「x」の前に番号を取得する方法は?文字の前に言葉を取得するには?

私は.split('x')[0]を使ってみましたが、 'x'の前にすべてをつかみました。

123x // Gives 123 
123y+123x - // Gives 123 
123x+123x - // Gives 246 
+0

何だろう '' "-1x * 200X" '、' "10倍+ 30X * 2倍" の出力?? –

+0

期待される結果は何ですか? – guest271314

答えて

0

私は私が仕事になると思うの正規表現を使用して機能をテストしてみました。私は結果、関数の働きの説明、そして関数のコメント付きバージョンについて説明しました。

単純な項を加算したり減算したりするより複雑な代数は扱いません。私はそのためにhttps://newton.now.sh/を参照しています、それは単純化を扱うことができるAPIです(私は提携していません)。

結果:

console.log(coefficient("-x+23x"));  // 22 
console.log(coefficient("123y+123x")); // 123 
// replaces spaces 
console.log(coefficient("x + 123x")); // 124 
console.log(coefficient("-x - 123x")); // -124 
console.log(coefficient("1234x-23x")); // 1211 
// doesn't account for other letters 
console.log(coefficient("-23yx"));  // 1 

説明:

最初の関数は、スペースを削除します。その後、正規表現を使用して、「x」が後に続く数字のシーケンスを見つけます。正面に+/-がある場合、正規表現はそれを保持します。この関数は、これらの数値のシーケンスをループし、合計に加算します。 ECMAScriptの中に十分な賢さがあるかどうか私にはわからない

function coefficient(str) { 
    // all powerful regex 
    var regexp = /(\+|-)?[0-9]*x/g 

    // total 
    sum = 0; 

    // find the occurrences of x 
    var found = true; 
    while (found) { 
    match = regexp.exec(str); 
    if (match == null) { 
     found = false; 
    } else { 
     // treated as +/- 1 if no proceeding number 
     if (isNaN(parseInt(match[0]))) { 
     if (match[0].charAt(0) == "-") { 
      sum--; 
     } else { 
      sum += 1; 
     } 
     // parse the proceeding number 
     } else { 
     sum += parseInt(match[0]); 
     } 
    } 
    } 
    return sum; 
} 
0

console.log(match('123x+123y+456x', 'x')) 
 
console.log(match('123x+123y+456x', 'y')) 
 

 
function match(str, x) { 
 
    return str.match(new RegExp('\\d+' + x, 'g')).reduce((cur, p) => { 
 
    return cur + parseInt(p.substr(0, p.length - x.length)) 
 
    }, 0) 
 
}

1

あなたは次のことを試すことができます。

var a='123x'; 
 
var b='123y+123x'; 
 
var c='123x+123x'; 
 
var patternX = /(\d+)x/g; 
 

 
function result(res, value){ 
 
    return res += parseInt(value.replace('x', '')); 
 
} 
 

 
var first = a.match(patternX).reduce(result, 0); 
 
var second = b.match(patternX).reduce(result, 0); 
 
var third = c.match(patternX).reduce(result, 0); 
 

 
console.log(first); 
 
console.log(second); 
 
console.log(third);

0

:それに数字を持っていない「x」はあります場合は、その係数は、-1または1

コメントコードとします正規表現を振り返るが、と一致する場合はとなり、 "x"を削除する処理が行われます。

用語を合計する場合は、を使用してさらに操作すると、が減ることが必要です。 xをトリミングするとreduceと組み合わせることができるので、マップは不要です。

console.log(
 
    '123x+123x'.match(/\d+x/ig).map(function(v){ 
 
    return v.slice(0,-1) 
 
    }).reduce(function(sum, v){return sum + +v},0) 
 
);

関連する問題