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,因此不能依赖 ()
在本例中捕获组。
更多的模式是:
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
或 正则表达式 =/#?|\.*/g
请解释一下。
最佳答案
#?
匹配字符串中的每个位置,因为空字符串仍被视为匹配。 .
在匹配 \.
之前先匹配 #?
,最终得到的结果是空字符串和散列(如果有的话)。
如果您尝试解析 CSS 选择器,请不要使用正则表达式。只需编写您自己的解析器即可。
关于Javascript正则表达式奇怪的行为 String.match(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18203038/