簡體   English   中英

如果一組不匹配,.match()返回null

[英].match() returns null if one group doesn't match

我要檢查幾個包含字母數字子字符串的字符串,並且可能在方括號中包含一個列表,其中各項之間用“:”分隔

例:

"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" ] 

如果可能的話,超棒的答案將按正則表達式拆分列表。

您可以同時使用兩個部分:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM