我要检查几个包含字母数字子字符串的字符串,并且可能包含括号中的列表,其中条目以“:”分隔
示例:
"this(is:an:example)"
"thisAsWell"
首先,我搜索 alphasubstring 和列表,然后将列表分解为数组。
.match(/([a-z]*)\((.*)\)/)
.spit(":")
适用于同时包含字母数字和列表的字符串,但如果缺少其中一个,则效果不佳。
示例:
// .match(...)
"abc"
-> [ "abc" , null , null ]
"abc(1,2,3)"
-> [ "abc(1,2,3)" , "abc" , "1:2:3" ]
"(1:2:3)"
-> [ "(1:2:3)" , null , null ]
如何最好地处理它,可选地检查两个子字符串? 我正在考虑可能的返回,例如:
"abc"
-> [ "abc" , "abc" , null ]
"abc(1,2,3)"
-> [ "abc(1,2,3)" , "abc" , "1:2:3" ]
"(1:2:3)"
-> [ "(1:2:3)" , null , "1:2:3" ]
如果可能的话, super 棒的答案会根据正则表达式拆分列表。
最佳答案
您可以选择使用这两个部分:
var re = /(?=.)([a-z]*)(?:\(([^)]*)\))?/
(?=.)
是前瞻,以确保我们不匹配空输入。
测试:
abc".match(re)
["abc", "abc", undefined]
"abc(1,2,3)".match(re)
["abc(1,2,3)", "abc", "1,2,3"]
"(1,2,3)".match(re)
["(1,2,3)", "", "1,2,3"]
"".match(re)
null
关于javascript - 如果一组不匹配,.match() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32625172/