如何用添加的条件替换部分字符串

时间:2017-03-26 00:14:50

标签: string if-statement replace conditional-statements

我希望用另一个字符串替换字符串的一部分,但前提条件是先满足条件。一个例子如下:

data_melted <- melt(data, id.vars = c("company", "sub.industry"), measured.vars = c("2006","2007","2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016"), variable = "Year", value.name="income")

我想获得string ='np.tan(x)* np.arctan(x)'`

我该如何使用

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

仅当string.replace('tan','np.tan')前面没有'tan'

'arc'

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

打印字符串

感谢您的任何建议

2 个答案:

答案 0 :(得分:0)

您可以使用正则表达式来解决您的问题。以下代码是在javascript中。因为,你没有提到你正在使用的语言。

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

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

答案 1 :(得分: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