mocca12345
mocca12345

Reputation: 11

Regex javascript match a function from string of functions

I have this string:

0;for(var b=0;32>b;b++)if(a&1<<31-b)return b;return 32});Math.Fb=Math.clz32;var xa=Math.abs,Hb=Math.cos,Ib=Math.sin,Jb=Math.atan2,Oa=Math.ceil,vb=Math.floor,Kb=Math.pow,ub=Math.min,K=0,Fa=null,aa=null;c.addRunDependency=Da;c.removeRunDependency=Ea;c.preloadedImages={};c.preloadedAudios={};var J=null,M=[function(a){var b=new WebSocket(w(a));b.binaryType="arraybuffer";b.events=[];b.onopen=function(){b.events.push([2,0,0]);va()};b.onerror=function(){b.events.push([3,0,0]);va()};b.onclose=function(){b.events.push([4,0,0]);va()};b.onmessage=function(a){a=new Uint8Array(a.data);var c=A(a.length);ka(a,c);b.events.push([1,c,a.length]);va()};for(a=0;a>2]=a[1];p[d>>2]=a[2];return a[0]},function(a,b,d,c,e){n.g[a].clearRect(b,d,c,e)},function(a,b,d){a=n.g[a].canvas;p[b>>2]=a.width;p[d>>2]=a.height},function(a,b,d){a=n.g[a].canvas;a.width=b;a.height=d},function(a){n.g[a].save()},function(a,b,d){n.g[a].translate(b,d)},function(a,b,d){n.g[a].scale(b,d)},function(a){n.g[a].restore()},function(a,b,d,c){n.g[a].fillStyle="rgb("+b+", "+d+","+c+")"},function(a,b,d,c,e){n.g[a].fillRect(b,d,c,e)},function(a,b,c,e){n.g[a].strokeStyle="rgb("+b+" , "+c+" ,"+e+")"},function(a,b){n.g[a].globalAlpha=b},function(a){n.g[a].beginPath()},function(a,b,c){n.g[a].moveTo(b,c)},function(a,b,c){n.g[a].lineTo(b,c)},function(a){n.g[a].stroke()},function(a,b){n.g[a].rotate(b)},function(a,b,c,e){n.g[a].drawImage(n.g[b].canvas,c,e)},function(a){n.g[a].fill()},function(){var a=document.getEl

Using regex, how do I extract function(a,b,d,c){n.g[a].fillStyle="rgb("+b+", "+d+","+c+")"} from it?

This is the regex I have come up so far: /function\((.*)\).*fillStyle.*?}/

The problem with the regex above is that it selects all the way from the first function it found and not just the function I want.

Upvotes: 0

Views: 80

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627022

If there can be no ( and ) inside the function signature, and { and } inside the function body, you may use

/function\(([^()]*)\){[^{}]*fillStyle[^{}]*}/

See this regex demo

The idea is that you can use negated character classes [^()] and [^{}] in order not to overflow function boundaries.

A safer regex will be the one that matches from ( up to ){ and then from { up to },:

/function\(([^)]*(?:\)(?!{)[^)]*)*)\){[^f}]*(?:}(?!,)[^}f]*|f(?!illStyle)[^}f]*)*fillStyle[^}]*(?:}(?!,)[^}]*)*}/

See another regex demo

The idea is to use an unrolled tempered greedy token, one is [^)]*(?:\)(?!{)[^)]*)* (to match up to )}), the second one is [^f}]*(?:}(?!,)[^}f]*|f(?!illStyle)[^}f]*)* to match all text that is not }, and not fillStyle, and the third one is [^}]*(?:}(?!,)[^}]*)* to match all text that is not },.

Upvotes: 1

Related Questions