LPR
LPR

Reputation: 390

How to replace part of a string with an added condition

The problem:

The objective is to convert: "tan(x)*arctan(x)"

Into: "np.tan(x)*np.arctan(x)"

What I've tried:

s = "tan(x)*arctan(x)"
s = s.replace('tan','np.tan')
Out: np.tan(x)*arcnp.tan(x)

However, using pythons replace method resulted in arcnp.tan.

Taking one additional step:

s = s.replace('arcnp.', 'np.arc')
Out: np.tan(x)*np.arctan(x)

Achieves the desired result... but this solution is sloppy and inefficient.

Is there a more efficient solution to this problem?

Any help is appreciated. Thanks in advance.

Upvotes: 0

Views: 73

Answers (2)

Toto
Toto

Reputation: 91508

Here is a way to do the job:

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

Explanation:

/               : 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

Replace:

$&  : means the whole match, ie. tan or arctan 

Upvotes: 1

ajai Jothi
ajai Jothi

Reputation: 2294

You can use regular expression to solve your issue. Following code is in javascript. Since, u didn't mention the language you are using.

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

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

Upvotes: 1

Related Questions