Javascript正则表达式奇怪的行为String.match()

时间:2013-08-13 07:25:59

标签: javascript regex

pattern = "p.class1.class2#id1";

regex   =  /#?|\.+/g;
pattern.match(regex) ;

//Outputs ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "#", "", "", "", ""]

//Now If I change regex to something like this
regex   =  /#|\.+/g ;
pattern.match(regex);  //Then it gives the correct output 

//Outputs [".", ".", "#"]

//Again If I change regex to something like this
regex   =  /\#|\.*/g;
pattern.match(regex);  //Then it again shows the weird behavior

//Outputs  ["", ".", "", "", "", "", "", "", ".", "", "", "", "", "", "", "#", "", "", "", ""]

//and at last with this regex combination 
regex  =  /\#?|\.*/g;
pattern.match(regex) ; //Its agains outputs something odd

//Outputs ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "#", "", "", "", ""];

我实际需要从给定的#字符串中打印.pattern的正确顺序,其中

# : Is optional i.e repeat 0 or 1 times
. : Would repeat 0 or more times

由于# and .可以按照模式中的任何顺序出现,而且我想要的是打印正确的顺序a / c到它们在字符串中的出现,所以不能依赖() <在这种情况下,强>捕获群组。

更多模式是:

pattern_1 = "p#id.class1.class2"` `//Correct output ['#','.','.']
pattern_2 = ".class1#id.class2"`  `//Correct output ['.','#','.']
pattern_3 = ".class1.class2"`      `//Correct output ['.','.']

我使用regex = /#|\.+/g获取此输出但不知道当我使用这些regex = /#?|\.+/g regex = /#?|\.*/g时发生了什么 请解释一下。

1 个答案:

答案 0 :(得分:2)

#?匹配字符串中的每个位置,因为空字符串仍被视为匹配。 .匹配#?之前匹配\.,最后会得到空字符串的结果,如果有空字符串则会产生哈希值。

如果您正在尝试解析CSS选择器,请不要使用正则表达式。只需编写自己的解析器。

相关问题