简体   繁体   中英

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.

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.

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 . It will split 54 into one match with 5 and one match with 4 . What I want it to do is to split 54 , 13 , 15 into groups. 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.

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+)?$

 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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