2
var string = "M-84.1487,-15.8513 a22.4171,22.4171 0 1 0 0,31.7026 h168.2974 a22.4171,22.4171 0 1 0 0,-31.7026 Z";
var regex = "[a-zA-Z][0-9, /-/.]*";
var array = string.match(regex);

Can anyone help me with my regular expression to match individual intructions (array[0] == "M-84.1487,-15.8513"; array[1] == "a22.4171,22.4171 0 1 0 0,31.7026";)

Thanks a lot

Tom
  • 43
  • 2
  • 5

1 Answers1

3

According to the BNF description you can identify an instruction as a letter followed by anything that is not a letter.

var pathData = "M-84.1487,-15.8513 a22.4171,22.4171 0 1 0 0,31.7026 h168.2974 a22.4171,22.4171 0 1 0 0,-31.7026 Z";
var pathSegmentPattern = /[a-z][^a-z]*/ig;
var pathSegments = pathData.match(pathSegmentPattern);

Of course you may want to trim the results, but that shouldn't be too hard.

Also try not to name your variables so meaningless (string, regex, array). In my opinion that's worse than naming them a, b or c.

Community
  • 1
  • 1
Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
  • 1
    Thanks, I'll give this a try. The variables are just named that way for the sake of this post :) – Tom Jan 13 '11 at 15:45
  • @Tom No problem. Let me know if you find anything wrong with this method. It's pretty straight-forward, but from what I could tell from the documentation you don't need anything more complex. – Alin Purcaru Jan 13 '11 at 15:59
  • How could I put a space after the letters? pathData = pathData.replace(/[a-z]/ig , ?+" "); What should I put in place of the question mark? – Tom Jan 13 '11 at 17:14
  • `pathData.replace(/[a-z]/ig , "$& ")` [Learn more.](http://www.regular-expressions.info/javascript.html) – Alin Purcaru Jan 13 '11 at 22:59
  • 2
    A bit late, but for visitors, i made a library to deal with SVG Pathes that is more secure than using a RegExp : https://github.com/nfroidure/SVGPathData – nfroidure Apr 05 '14 at 12:52
  • This has a slight problem in that it will match exponents as a command, `/[a-df-z][^a-df-z]*/ig` will only swallow exponents in the command body. – misnomer Sep 05 '15 at 11:53
  • "If a moveto is followed by multiple pairs of coordinates, the subsequent pairs are treated as implicit lineto commands." So this regex will not properly separate something like "M 0,0 2,3" as "M 0,0" and (with implied "L")"2,3" – grantpatterson Aug 23 '20 at 22:38