Pangolin
Pangolin

Reputation: 7444

Javascript Regex Check if string has word that does not belong

I have a string with times (formatted HH:MM) each on a new line. I want to create a JS function to check if there is any times that does not belong. It should simply return true or false.

Example correct string: var s = "5:45\n07:00\n13:00\n17:00";

5:45
07:00
13:00
17:00

Example incorrect string: var s = "5:45\n07:00\n55:00\n17:00";

5:45
07:00
55:00 // incorrect date here, should return false
17:00

My regex experience is little to none. Playing around on Scriptular I created this expression to detect times that do match: /^[0-2]?[0-9]\:[0-5][0-9]$/m. This however is not sufficient.

So, how can I get this to work with a string s as indicated above?

function checkIfStringConforms(s)
{
  var all_good = [some magic with regex here]
  return all_good;
}

PS: I have Googled around and checked answers on SO. My regex skill is... eh.

Upvotes: 2

Views: 137

Answers (3)

ermouth
ermouth

Reputation: 844

/(((2[^0-3]|[3-9].):..)|(..?:[^0-5].))(\n|$)/

Regexp returns true if your s var has at least one invalid time. Please, check it carefully before use – your question is quite broad and restrictions are not fully defined. Regex assumes that you have something like x:xx or xx:xx in each line (x is a digit) – I’m not sure this assumption covers all your data.

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

It can be done without the use of any regex. Just split on new-line and see if every date matches your format. For that we could use Array.every

function checkIfStringConforms(s) {
    return s.split("\n").every(function(str){
        var arr = str.split(":");
        return (arr[0] < 24 && arr[0] > -1) && arr[1] < (60 && arr[1] > -1)
    });
}

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

Your regex is OK, but it would also match 29:00, so it needs some improvement. Then, it's always a bit more difficult to find non-matches than it is to find matches. You could try and remove all matches from the string and then see if it's empty (except for whitespace):

result = s.replace(/^(?:2[0-3]|[01]?[0-9]):[0-5][0-9]$/mg, "");

If result is empty after that, there were no illegal times in your string.

Upvotes: 1

Related Questions