2017-03-26 7 views
0

文字列の一部を別の文字列に置き換えることを検討していますが、条件が最初に満たされている場合のみです。例は次のようになります。文字列の一部を追加条件に置き換える方法

string='tan(x)*arctan(x)'

私は= 'np.tan(x)は* np.arctan(X)' `

がどのように私は

string.replace('tan','np.tan')を使用することができます文字列を取得したいです

'tan'の前に'arc'がない場合のみ?何かアドバイス

答えて

0

ため

string=string.replace('tan','np.tan')

string=string.replace('arctan','np.arctan')

印刷文字列

おかげであなたはあなたの問題を解決するために、正規表現を使用することができます。次のコードはjavascriptにあります。あなたが使っている言語については言及していないので、ここで

var string = 'tan(x)*arctan(x)*xxxtan(x)'; 
 

 
console.log(string.replace(/([a-z]+)?(tan)/g,'np.$1$2'));

0

仕事をするための方法である:

var string = 'tan(x)*arctan(x)'; 
 
var res = string.replace(/\b(?:arc)?tan\b/g,'np.$&'); 
 
console.log(res);

説明:

/    : regex delimiter 
    \b   : word boundary, make sure we don't have any word character before 
    (?:arc)? : non capture group, literally 'arc', optional 
    tan   : literally 'tan' 
    \b   : word boundary, make sure we don't have any word character after 
/g    : regex delimiter, global flag 

置き換え:

$& : means the whole match, ie. tan or arctan 
関連する問題