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

标签 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

由于 # 和 . 可以以任何顺序出现在模式中,而我想要的只是打印它们在字符串中出现的正确顺序 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/

相关文章:

javascript - JavaScript 中的行继续符

javascript - JQuery 不在 For 循环内执行

javascript - Javascript 中区分大小写的重音折叠

javascript - 逆向工程正则表达式模式以查找 token 数和预期匹配的长度

适用于英国移动设备的 Javascript 正则表达式

JavaScript - 凯撒密码

javascript - Ext.form.TextField : getValue() works but setValue(. ..) 不...为什么?

javascript - 返回上一个 "this"

php - 错误消息自动隐藏/消失并在POST后停留在输入/表单页面上

javascript - 重写正则表达式以用于比较?