2012-07-20 123 views
-3

的越来越部分我有很多像琴弦正则表达式和字符串

blip createBlip (float x, float y, float z, [int icon=0, int size=2, int r=255, int g=0, int b=0, int a=255, int ordering=0, float visibleDistance=99999.0, visibleTo = getRootElement()]) 

float float float getElementRotation (element theElement [, string rotOrder = "default" ]) 

我需要得到份该字符串的,像

array(
[1] = blip 
[2] = createBlip 
[3] = x 
[4] = y 
[5] = z 
) 

array(
[1] = blip createBlip 
[2] = float x 
[3] = float y 
[4] = float z 
[5] = int icon=0 
[6] = int size=2 
[7] = int r=255 

.. 。

用正则表达式可以做到这一点吗?如果是,如何?

+0

我想函数参数的数量是动态的吗?有可能的。你试过什么了? – 2012-07-20 17:34:42

+0

>> ***我需要......请帮助我。*** <<向我们展示您的代码(到目前为止)。 – 2012-07-20 17:39:43

+0

请指定输入格式。从你提供的两个例子中可以看不出来。 – oberlies 2014-05-08 15:00:09

回答

1

我认为你可以用正则表达式组和javascript String.match()方法,例如(1弦)做到这一点:

var string = "blip createBlip (float x, float y, float z, [int icon=0, int size=2, int r=255, int g=0, int b=0, int a=255, int ordering=0, float visibleDistance=99999.0, visibleTo = getRootElement()])"; 

var result = string.match(/((?:(?:\w+)\s?)+?)\(?\[?((?:(?:(?:(?:\s?\w+)+))\,)+)\s?\[((?:(?:(?:\s?=?\.?\(?\)?\w?)+)\,?)+)\]\s?\)/); 

结果将是一个数组:

["blip createBlip (float x, float y, float z, [int icon=0, int size=2, int r=255, int g=0, int b=0, int a=255, int ordering=0, float visibleDistance=99999.0, visibleTo = getRootElement()])", "blip", "createBlip", " float x, float y, float z,", "int icon=0, int size=2, int r=255, int g=0, int b=0, int a=255, int ordering=0, float visibleDistance=99999.0, visibleTo = getRootElement()"] 

现在,result [0]包含完全匹配,但结果[1] .. result [n](n - 捕获组的数量)包含带有()和[]括号内参数的字符串。现在你可以用“,”分隔“float x,float y,float z”,只获取参数。

您应该尝试概括该模式,以便它匹配第二个字符串和其他字符串。它看起来有点疯狂,但它现在是我唯一想到的解决方案...