Home > Blockchain >  Regex match everything not between a pair of characters
Regex match everything not between a pair of characters

Time:09-30

Suppose a string (representing elapsed time in the format HH:MM:ss) like this:

"123:59:00"

I want to match everything except the numbers for the minutes, i.e.: the regex should match the bold parts and not the number between colons:

"123: 59 :00"

In the example, the 59 should be the only part unmatched. Is there any way to accomplish this with a js regex?

EDIT: I'm asking explicitly for a regex, because I'm using the Notion Formula API and can only use JS regex here.

CodePudding user response:

Using split() might be the most canonical way to go, but here is a regex approach using match():

var input = "123:59:00";
var parts = input.match(/^[^:] |[^:] $/g);
console.log(parts);

If you want to also capture the trailing/leading colons, then use this version:

var input = "123:59:00";
var parts = input.match(/^[^:] :|:[^:] $/g);
console.log(parts);

CodePudding user response:

You don't necessarily need to use RegEx for this. Use split() instead.

const timeString = "12:59:00";
const [hours, _, seconds] = timeString.split(":");
console.log(hours, seconds);

If you want to use Regex you can use the following:

const timeString = "12:00:59";
const matches = timeString.match(/(?<hours>^\d{2}(?=:\d{2}:))|(?<seconds>(?<=:\d{2}:)\d{2}$)/g);

console.log(matches);

// if you want to include the colons use this
const matchesWithColons = timeString.match(/(?<hours>^\d{2}:(?=\d{2}:))|(?<seconds>(?<=:\d{2}):\d{2}$)/g);
console.log(matchesWithColons);

You can drop the named groups ?<hours> and ?<seconds>.

CodePudding user response:

Could also work

^([0-9]{2})\:[0-9]{2}\:([0-9]{2})$/mg
  • Related