Regular expression in javascript to check time with date - javascript

I need to check whether the text contains a date part with it.
for ex: mytext_12/26/2011_11:51_AM or someText_12/26/2011_13:51_PM have a date part it returns true.
I am not too good with expressions so looking for one. the format of the date - time part is fixed.
i got a way out for it but failing for time .
var containsDate = ~str.search(/\d{1,2}\/\d{1,2}\/\d{4}/);
it checks the date part perfectly but when i am trying for the time part i am messing it up some where .
_\d{1,2}:\d{2}_(?:AM|PM) this is the part for time but i am not able to generate the final regex by combining this two.

Try,
.search(/[0-9]{2}\/[0-9]{2}\/[0-9]{4}_[0-9]{2}:[0-9]{2}_(AM|PM)/)
A good resource for regex,
MDN:Regular Expressions

Try,
.search(/\d+\/\d+\/\d{4}_\d+:\d+_(AM|PM)/)

Related

Regex to find functions with a single parameter in editors [duplicate]

I'm trying to use a powershell regex to pull version data from the AssemblyInfo.cs file. The regex below is my best attempt, however it only pulls the string [assembly: AssemblyVersion(". I've put this regex into a couple web regex testers and it LOOKS like it's doing what I want, however this is my first crack at using a powershell regex so I could be looking at it wrong.
$s = '[assembly: AssemblyVersion("1.0.0.0")]'
$prog = [regex]::match($s, '([^"]+)"').Groups[1].Value
You also need to include the starting double quotes otherwise it would start capturing from the start until the first " is reached.
$prog = [regex]::match($s, '"([^"]+)"').Groups[1].Value
^
Try this regex "([^"]+)"
Regex101 Demo
Regular expressions can get hard to read, so best practice is to make them as simple as they can be while still solving all possible cases you might see. You are trying to retrieve the only numerical sequence in the entire string, so we should look for that and bypass using groups.
$s = '[assembly: AssemblyVersion("1.0.0.0")]'
$prog = [regex]::match($s, '[\d\.]+').Value
$prog
1.0.0.0
For the generic solution of data between double quotes, the other answers are great. If I were parsing AssemblyInfo.cs for the version string however, I would be more explicit.
$versionString = [regex]::match($s, 'AssemblyVersion.*([0-9].[0-9].[0-9].[0-9])').Groups[1].Value
$version = [version]$versionString
$versionString
1.0.0.0
$version
Major Minor Build Revision
----- ----- ----- --------
1 0 0 0
Update/Edit:
Related to parsing the version (again, if this is not a generic question about parsing text between double quotes) is that I would not actually have a version in the format of M.m.b.r in my file because I have always found that Major.minor are enough, and by using a format like 1.2.* gives you some extra information without any effort.
See Compile date and time and Can I generate the compile date in my C# code to determine the expiry for a demo version?.
When using a * for the third and fourth part of the assembly version, then these two parts are set automatically at compile time to the following values:
third part is the number of days since 2000-01-01
fourth part is the number of seconds since midnight divided by two (although some MSDN pages say it is a random number)
Something to think about I guess in the larger picture of versions, requiring 1.2.*, allowing 1.2, or 1.2.3, or only accepting 1.2.3.4, etc.

Javascript substring check using indexOf or search on a date string with forward slash /

I am surprised to not to find any post regarding this, I must be missing something very trivial. I have a small JavaScript function to check if a string matches an object's properties. Simple stuff right? It works easily with all strings except those which contain a forward slash.
"‎04‎/‎08‎/‎2015‎".indexOf('4') // returns 2 :good
"‎04‎/‎08‎/‎2015‎".indexOf('4/') // returns -1 :why?
The same issue appears to be with .search() function as well. I encountered this issue while working on date strings.
Please note that I don't want to use regex based solution for performance reasons. Thanks for your help in advance!
Your string has invisible Unicode characters in it. The "left-to-right mark" (hex 200E) appears around the two slash characters as well as at the beginning and the end of the string.
If you type the code in on your browser console instead of cutting and pasting, you'll see that it works as expected.

Javascript regular expression does not match till the end of the string

I am validating dates using regular expression in javascript. The regular expression I am using is
/^(((((0?[1-9])|(1\d)|(2[0-8]))\/((0?[1-9])|(1[0-2])))|((31\/((0?[13578])|(1[02])))|((29|30)\/((0?[1,3-9])|(1[0-2])))))\/((20[0-9][0-9])|(19[0-9][0-9])))|((29\/02\/(19|20)(([02468][048])|([13579][26]))))$/
This matches dates accurately but it would match values such as
1/1/2001ff even though I am using $ to mark the end of string.
But if I give values like ff1/1/2001 it would invalidate it. So it's considering the start of the string and ignore the end of string part.
Does anyone know the reason for this.
From: Detecting an "invalid date" Date instance in JavaScript
if ( Object.prototype.toString.call(d) === "[object Date]" ) {
// it is a date
if ( isNaN( d.getTime() ) ) { // d.valueOf() could also work
// date is not valid
}
else {
// date is valid
}
}
else {
// not a date
}
Logically, it makes much more sense to check if the date is valid rather than using a regex to match a date. However, if you're trying to search for dates, your regex still works (I tested it in Notepad++ find for example.) Other than that, like the comment said, there's no reason to have such a complicated regex.
As correctly pointed out by Dracs, the issue was with missing brackets. Thank you very much for pointing that out.
The reason for not using javascript date object is we need only to allow mm/dd/yyyy format in the textbox. So it would be easy to use a regex to validate textbox.

jQuery - check proper time format

I have an input field where the user enters a time in format mm:hh. The format is specified inside the field (default value 09:00) but I still want to perform a client-side check to see if the format is correct.
Since the existing client-side validation is in jQuery, I'd like to keep this in jQuery as well.
I'm mainly a PHP programmer so I need some help writing this one in an optimal manner.
I know I can check each individual character (first two = digits, third = ':', last two = digits) but is there a way to do it more elegantly, while also checking the hour count is not larger than 23 and the minute count isn't larger than 59?
In PHP I would use regular expressions, I assume there's something similar for jQuery?
Something like this makes sense to me:
([01]?[0-9]|2[0-3]):[0-5][0-9]
But I'm not too familiar with jQuery syntax so I'm not sure what to do with it.
you can use regex in JavaScript too:
http://www.w3schools.com/jsref/jsref_obj_string.asp
use
.search() - http://www.w3schools.com/jsref/jsref_search.asp
or .match() - http://www.w3schools.com/jsref/jsref_match.asp
or .replace() - http://www.w3schools.com/jsref/jsref_replace.asp
EDIT:
<script>
var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
var correct = ($('input').val().search(regexp) >= 0) ? true : false;
</script>
EDIT2:
here the documentation of regexpobject in javascript:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
<script>
var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
var correct = regexp.test($('input').val());
</script>
EDIT3:
fixed the regexp
In JavaScript, regexes are delimited by /. So you would do...
var isValidTime = /([01]?[0-9]|2[0-3]):[0-5][0-9]/.test(inputString);
Your regex seems to make sense for validating any 24H time in HH:mm format. However as I state in my comment under Andreas's answer - this will return true if any part of the string matches. To make it validate the entire string, use anchors to match the start and end of the string also eg...
var isValidTime = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(inputString);
To actually pull the matches you would need to use the string.match JS function.
Oh - and please be aware that jQuery is Javascript - it's just a library of very useful stuff! However this example contains no reference to the jQuery library.
In JavaScript you can use yourstring.match(regexp) to match a string against a regular expression.
I have very limited RegEx-experience, so I cant help you with the pattern, but if you have that set .match() should be all it takes.
A different approach, but using an extra javascript lib instead of regular expressions:
var valid = moment(timeStr, "HH:mm", true).isValid();
I guess if you already use moment.js in your project, there's no downside.
And since you didn't specifically request an answer using regular expressions, I think it's valid to mention.

How to use this regular expression in JavaScript?

I am trying to use the following regular expression to test for a valid date.
^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$
which I got from
http://regexlib.com/REDetails.aspx?regexp_id=1071
My JavaScript test code is:
var date='1/1/1965';
var re = new RegExp('^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$');
alert(re.test(date));
I keep getting "false" rather than "true" for this valid test date.
Try this:
var date='1/1/1965';
var re = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])\/(29|30)|(0?[13578]|1[02])\/31)\/(19|[2-9]\d)\d{2}|0?2\/29\/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/;
alert(re.test(date));
Your problem might be escaping of the slashes.
There are 2 ways you can insert a regexp in javascript. 1st way is just put it in forward slashes, and the second way, which is the way you are doing it is with RegExp object, which means that you then have to include the regexp string itself in the JavaScript code as a string.
And as every other string in Javascript which contains special characters like backward slashes (which your regexp does), you have to escape them with yet another backslash.
So basically just replace every backslash in your code with double backslash (\\) and you should be fine.
Just put it in forward-slashes:
var re = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)\/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/
Now, while that'll get you a regular expression to use, I have to say that this may be one of the silliest applications of a regex ever. You'd be way better off just instantiating a JavaScript "Date" object and using it's surprisingly friendly API to check what you need to check.
If you instantiate a JavaScript "Date" object with a bogus date (like Februrary 30), it'll just roll to the actual date that sort-of corresponds to the bogus date; in other words, it carries over the bogus days into the next month. Thus, if you just hold on to the month and day, and create a "Date" instance, you can know that if the month and day that the "Date" instance gives you when you ask are different from the ones you fed it, then the original date must have been unreal.

Categories