Jamgreen Jamgreen - 1 month ago 6
Javascript Question

Regex to replace function in string

I have a string

Apply the function K(i, x<=>k) for more info.


I want to convert
K(i, x<=>k)
to
K_{i}(x<>k)
, but the arguments inside the function
K
can vary, so I guess it is something like

string.replace(/\K\([.?],[.?]\)/g, 'K_{$1}($2)')


Edit



Sorry for the vague explanation of what the arguments for K can be. I just thought the regex would be faster if it didn't specify what the arguments could be, but just had some placeholders.

The first argument of K can be only be numbers and letters and the second argument of K can be numbers, letters, spaces, ->, <->, [], <>, &, | and ~, and there can never be more than 2 arguments, so the pattern is always K(something, something).

The remaining string varies as well. So a string could also look like
I have a function K(i,a) and two other functions K(3,p&s |r) and K(f, ~g)

Answer

May be something like that (you forgot to group args for the replace value):

string.replace(/K\(([a-zA-Z0-9]+), ?(.+)\)/g, 'K_{$1}($2)')