Jamgreen Jamgreen - 3 months ago 16
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)
, but the arguments inside the function
can vary, so I guess it is something like

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


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)


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)')