gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:10:41 27 4
gpt4 key购买 nike

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 regex =/#?|\.*/g
请解释。

最佳答案

#? 匹配字符串中的每个位置,因为空字符串仍被视为匹配项。 . 在匹配 \. 之前先匹配 #? ,最后得到的结果是空字符串和散列(如果有的话)。

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

关于Javascript 正则表达式奇怪的行为 String.match(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18203038/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com