简体   繁体   English

正则表达式拆分可选组

[英]Regular expression splitting a optional group

I have tried to set up a regular expression in JavaScript that would accept a string like 12:13:14.15 (at max) but when doing just 12:13 , it will split the first match (12) into two matches. 我试图在JavaScript中设置一个正则表达式,该表达式可以接受12:13:14.15类的字符串(最大),但是仅执行12:13 ,它将把第一个匹配项(12)拆分为两个匹配项。

I've been at this for some time now and I can't figure out what is causing this. 我已经来了一段时间,我不知道是什么原因造成的。

This is the expression I'm using: 这是我正在使用的表达式:

^(\d+)?:?(\d+):(\d+).?(\d+)?$

From what I've tried, it supposed to be set up like this: 根据我的尝试,应该这样设置:

  • (XX:)XX:XX(.XX) , where () is optional. (XX:)XX:XX(.XX) ,其中()是可选的。

As I mentioned above, filling the whole thing out works and everything gets into their respective matches. 正如我上面提到的,将整个内容填写完整,所有内容都进入各自的匹配项。 But leaving out the first optional part causes it to split the first match into two matches. 但是如果忽略了第一个可选部分,则会导致将第一个匹配项拆分为两个匹配项。


For example: 例如:

The full string is 54:13.15 . 完整的字符串是54:13.15 It will split 54 into one match with 5 and one match with 4 . 它将把54分为5场比赛和4场比赛。 What I want it to do is to split 54 , 13 , 15 into groups. 我希望它做的是分裂541315成组。 It should split by every : and . 它应该由每一个分裂:. .

Mind you, this example is WITHOUT the optional part. 请注意,此示例没有可选部分。 With the optional part included, it will split correctly. 包括可选部分,它将正确分割。

I also need to go with regular expressions because I need to restrict the number of splits it can do. 我还需要使用正则表达式,因为我需要限制它可以执行的拆分次数。 I don't want it to be able to have multiple . 我不希望它可以有多个. splits or like 10 : splits. 分裂或类似10 :分裂。

Any help with this is appreciated! 感谢您提供任何帮助!

I think you are making this more complicated than it needs to be. 我认为您正在使这一过程变得比所需的复杂。 You can just match the delimiters that you want to split on. 您可以匹配要分割的定界符。 You don't need to capture the rest. 您无需捕获其余部分。 Fore example: 前例:

 let st = '54:13.15' // split on : and . console.log(st.split(/[:.]/)) st = '12:13:14.15' console.log(st.split(/[:.]/)) st = '12:13:14' console.log(st.split(/[:.]/)) 

You can use the regular expression: 您可以使用正则表达式:

^(\\d+)?:?(\\d+)?:(\\d+).?(\\d+)?$ ^(\\ d +):?(\\ d +):???(\\ d +)(\\ d +)$

 var timestamp = '12:13:14.15' var re = /^(\\d+)?:?(\\d+)?:(\\d+)\\.?(\\d+)?$/g matches = re.exec(timestamp) ms = matches[4] console.log(ms) var timestamp = '54:13.20' var re = /^(\\d+)?:?(\\d+)?:(\\d+)\\.?(\\d+)?$/g matches = re.exec(timestamp) ms = matches[4] console.log(ms) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM