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
由于可以在模式中以任何顺序出现,我想要的只是打印正确的顺序 a/c 到它们在字符串中的出现,所以在这种情况下# and .
不能依赖()
捕获组。
还有一些模式是:
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
请解释一下。