473,795 Members | 3,157 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

RegExp and how to use regular expressions

I have a page that accepts input from many textboxes. Many of the
textboxes are intended to accept dates and times, thus, I expect only
digits to be entered. I originally tested using parseInt and isNaN, but
I'm not even sure that the results are as perfect as I need. I am
expecting to use RegExp.test(str ing), but I'm not 100% sure about that,
either.
Here is a test program with a textbox that has a maxlength of 2
characters. The function evaluateIt() measures the string for length.
If 2 characters, it tests against the regular expression \d\d. If 1
character, it tests against \d. This seems to be effective, but isn't
there a way to check either of these cases with one test? I tried
if(test(oneDig) || test(twoDig)), but this will allow a string of 1
digit and one non-digit to pass.
Here is the test program as I wrote it.
<HTML>
<HEAD><TITLE>Ex perimenting with regular expressions and the RegExp
object</TITLE>
<SCRIPT language="javas cript">
function evaluateIt(sent String)
{
twoDig = new RegExp("\\d\\d" ,"g");
oneDig = new RegExp("\\d","g ");
if(sentString.l ength == 2)
{
if(twoDig.test( sentString))
{
alert("Two digits. All good.");
return;
}
else
{
alert("Two digits. Not good.");
return
}
} //closes if length==2
if(sentString.l ength == 1)
{
if(oneDig.test( sentString))
{
alert("One digit. All good.");
return;
}
else
{
alert("One digit. Not good.");
return;
}
} //closes if length==1
alert("Neither 1 nor 2 digits. Not good.");
return;
} //closes evaluateIt function
</SCRIPT>
</HEAD>
<BODY>
<FORM action="nothing .htm" method=POST>
<BR><BR>
Type something in the box to check against a regular expression
<INPUT type=text size=2 maxlength=2 name="thebox">< BR><BR>
<INPUT type=submit value="Do It"
onclick="evalua teIt(thebox.val ue);return false;">
</FORM>
</BODY>
</HTML>
Jul 23 '05 #1
10 2216
On Fri, 03 Sep 2004 14:01:41 -0700, Jeff Sandler
<ff*******@dsle xtreme.com> wrote:
I have a page that accepts input from many textboxes. Many of the
textboxes are intended to accept dates and times, thus, I expect only
digits to be entered. I originally tested using parseInt and isNaN, but
I'm not even sure that the results are as perfect as I need. I am
expecting to use RegExp.test(str ing), but I'm not 100% sure about that,
either.
The test method checks that the string matches the regular expression. It
is what's usually used in validation, and much better than isNaN.
Here is a test program with a textbox that has a maxlength of 2
characters. The function evaluateIt() measures the string for length.
If 2 characters, it tests against the regular expression \d\d. If 1
character, it tests against \d. This seems to be effective, but isn't
there a way to check either of these cases with one test? I tried
if(test(oneDig) || test(twoDig)), but this will allow a string of 1
digit and one non-digit to pass.


How about:

var digits = /^\d+$/;

if(digits.test( <string>)) {
// <string> only contains numbers
}

The regular expression, digits, ensures that the entire string is made up
of only digits. There must be at least one; there is no maximum limit. If
you want to impose one (though your HTML should do that for you), replace
'+' with {n,m} (including the braces). 'n' is the minimum number, whilst
'm' is the maximum. If you want exactly n digits, use {n}.

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2
Jeff Sandler wrote:
I have a page that accepts input from many textboxes. Many of the
textboxes are intended to accept dates and times, thus, I expect only
digits to be entered. I originally tested using parseInt and isNaN, but
I'm not even sure that the results are as perfect as I need. I am
expecting to use RegExp.test(str ing), but I'm not 100% sure about that,
either.
Here is a test program with a textbox that has a maxlength of 2
characters. The function evaluateIt() measures the string for length.
If 2 characters, it tests against the regular expression \d\d. If 1
character, it tests against \d. This seems to be effective, but isn't
there a way to check either of these cases with one test? I tried
if(test(oneDig) || test(twoDig)), but this will allow a string of 1
digit and one non-digit to pass.
Here is the test program as I wrote it.
<HTML>
<HEAD><TITLE>Ex perimenting with regular expressions and the RegExp
object</TITLE>
<SCRIPT language="javas cript">
function evaluateIt(sent String){
return /^[1-9]?\d$/.test(sentStrin g);
}
Won't accept a two digit number starting with "0", though.
Mick
function evaluateIt(sent String)
{
twoDig = new RegExp("\\d\\d" ,"g");
oneDig = new RegExp("\\d","g ");
if(sentString.l ength == 2)
{
if(twoDig.test( sentString))
{
alert("Two digits. All good.");
return;
}
else
{
alert("Two digits. Not good.");
return
}
} //closes if length==2
if(sentString.l ength == 1)
{
if(oneDig.test( sentString))
{
alert("One digit. All good.");
return;
}
else
{
alert("One digit. Not good.");
return;
}
} //closes if length==1
alert("Neither 1 nor 2 digits. Not good.");
return;
} //closes evaluateIt function
</SCRIPT>
</HEAD>
<BODY>
<FORM action="nothing .htm" method=POST>
<BR><BR>
Type something in the box to check against a regular expression
<INPUT type=text size=2 maxlength=2 name="thebox">< BR><BR>
<INPUT type=submit value="Do It"
onclick="evalua teIt(thebox.val ue);return false;">
</FORM>
</BODY>
</HTML>

Jul 23 '05 #3
Mick White wrote on 04 sep 2004 in comp.lang.javas cript:
function evaluateIt(sent String){
return /^[1-9]?\d$/.test(sentStrin g);
}
Won't accept a two digit number starting with "0", though.
Mick


This will even return true: 000007

return /^[1-9]?\d$/.test(+sentStri ng);

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress,
but let us keep the discussions in the newsgroup)

Jul 23 '05 #4
On 04 Sep 2004 08:35:02 GMT, Evertjan. <ex************ **@interxnl.net >
wrote:

[snip]
This will even return true: 000007

return /^[1-9]?\d$/.test(+sentStri ng);


Of course it will if you type-convert to a number first. I believe (I
can't check at the moment) the conversion will go something like:

'000007' --toInteger (+)--> 7 --toString (test())--> '7'

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
JRS: In article <10************ *@corp.supernew s.com>, dated Fri, 3 Sep
2004 14:01:41, seen in news:comp.lang. javascript, Jeff Sandler
<ff*******@dsle xtreme.com> posted :
I have a page that accepts input from many textboxes. Many of the
textboxes are intended to accept dates and times, thus, I expect only
digits to be entered. I originally tested using parseInt and isNaN, but
I'm not even sure that the results are as perfect as I need. I am
expecting to use RegExp.test(str ing), but I'm not 100% sure about that,
either.
Here is a test program with a textbox that has a maxlength of 2
characters. The function evaluateIt() measures the string for length.
If 2 characters, it tests against the regular expression \d\d. If 1
character, it tests against \d. This seems to be effective, but isn't
there a way to check either of these cases with one test? I tried
if(test(oneDig ) || test(twoDig)), but this will allow a string of 1
digit and one non-digit to pass.
Here is the test program as I wrote it.
...


Ugh!

OK = /^\d\d$/.test(S) // two digits
OK = /^\d?\d$/.test(S) // two digits, first optional
OK = /^\d\d?$/.test(S) // two digits, second optional
OK = /^\d{1,2}$/.test(S) // one or two digits

Note use of ^ & $.

You will also, I expect, want to validate those dates.

Read the FAQ on dates; see below; see also my js-valid.htm .

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #6
Michael Winter wrote:
On Fri, 03 Sep 2004 14:01:41 -0700, Jeff Sandler
<ff*******@dsle xtreme.com> wrote:
I have a page that accepts input from many textboxes. Many of the
textboxes are intended to accept dates and times, thus, I expect only
digits to be entered. I originally tested using parseInt and isNaN,
but I'm not even sure that the results are as perfect as I need. I
am expecting to use RegExp.test(str ing), but I'm not 100% sure about
that, either.

The test method checks that the string matches the regular expression.
It is what's usually used in validation, and much better than isNaN.
Here is a test program with a textbox that has a maxlength of 2
characters. The function evaluateIt() measures the string for
length. If 2 characters, it tests against the regular expression
\d\d. If 1 character, it tests against \d. This seems to be
effective, but isn't there a way to check either of these cases with
one test? I tried if(test(oneDig) || test(twoDig)), but this will
allow a string of 1 digit and one non-digit to pass.

How about:

var digits = /^\d+$/;

if(digits.test( <string>)) {
// <string> only contains numbers
}

The regular expression, digits, ensures that the entire string is made
up of only digits. There must be at least one; there is no maximum
limit. If you want to impose one (though your HTML should do that for
you), replace '+' with {n,m} (including the braces). 'n' is the minimum
number, whilst 'm' is the maximum. If you want exactly n digits, use {n}.

Hope that helps,
Mike

Mike,
Your input has helped tremendously. I have used your regular expression
many times in my code already. Now I have a new variation on my
original question.
I'm still doing the same script, only now, the user is allowed to enter
a real (floating point, float, whatever) number. Thus, the var digits
must now accept a decimal point at pretty much any position in addition
to digitis. Can this be done easily? Could it be something as simple
as changing the statement to read
var digits = /.,^d+$/
I should also point out that the user is allowed 7 characters in this
case unlike the last case where he was only allowed 2 characters.
Jul 23 '05 #7
On Fri, 10 Sep 2004 09:11:38 -0700, Jeff Sandler wrote:
Can this be done easily? Could it be something as simple
as changing the statement to read
var digits = /.,^d+$/


What happened when you tried that?

--
Andrew Thompson
http://www.PhySci.org/ Open-source software suite
http://www.PhySci.org/codes/ Web & IT Help
http://www.1point1C.org/ Science & Technology
Jul 23 '05 #8
On Fri, 10 Sep 2004 16:27:14 GMT, Andrew Thompson <Se********@www .invalid>
wrote:
On Fri, 10 Sep 2004 09:11:38 -0700, Jeff Sandler wrote:
Can this be done easily? Could it be something as simple
as changing the statement to read
var digits = /.,^d+$/


What happened when you tried that?


It might error. The carat (^) marks the beginning of the input. Characters
placed before it would be ignored, and might be regarded as a malformed
pattern.

Jeff, do you have any specific constraints, other than the maximum length?
For example, can the input accept an integer, or must it contain a period?
Do you require at least one number before and after the period?

This will accept, at a minimum, '0.0'. That is, it must contain a period.

function isReal(s) {
return /^\d+\.\d+$/.test(s) && 8 > s.length;
}

You can change the regular expression literal to

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

if an integer is also acceptable.

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #9
The constraints are exactly this:
The user is entering a dollar amount and is instructed to not enter
dollar signs nor commas. He may, however, enter a single period to
represent a decimal point. Thus, he must enter 1 thru 7 characters and
all must be either a digit or period. There can be either 0 or 1
periods and no more. A period at the last position is sort of
senseless, but acceptable still.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5495
by: | last post by:
Hi, I'm fairly new to regular expressions, and this may be a rather dumb question, but so far I haven't found the answer in any tutorial or reference yet... If I have f.i. the string "The {{{{power of {{{{regular expressions}}}} comes from}}}} the ability to include alternatives and repetitions in the pattern." from which I want to extract chunks starting with "{{{{" and ending with "}}}}".
2
2367
by: Ron Brennan | last post by:
Good morning. I would like to use one or more RegExp to validate country names as having the first and last words beginning with an uppercase letter, intermediate words beginning with either uppercase or lowercase, and all other characters being lowercase characters. The difficult part is that I want to obtain save the string positions of the invalid characters in an array, rather than just obtain a true or false value. Can anybody...
10
39358
by: Anand Pillai | last post by:
To search a word in a group of words, say a paragraph or a web page, would a string search or a regexp search be faster? The string search would of course be, if str.find(substr) != -1: domything() And the regexp search assuming no case restriction would be,
5
1835
by: Dr John Stockton | last post by:
ISTM that RegExps deserve a FAQ entry, with links to more detailed sources. An important question, probably not treated by many otherwise worthwhile sources, must be on feature detection of the newer RegExp facilities - for example, greedy/non-greedy. The answer may be that it is not possible to do so in a safe manner; that one can do no better than something like
8
2034
by: Dmitry Korolyov | last post by:
ASP.NET app using c# and framework version 1.1.4322.573 on a IIS 6.0 web server. A single-line asp:textbox control and regexp validator attached to it. ^\d+$ expression does match an empty string (when you don't enter any values) - this is wrong d+ expression does not match, for example "g24" string - this is also wrong www.regexplib.com test validator works fine for both cases, i.e. it is reporting "not match" for the...
7
1911
by: arno | last post by:
Hi, I want to search a substring within a string : fonction (str, substr) { if (str.search(substr) != -1) { // do something } }
9
6899
by: =?ISO-8859-1?Q?BJ=F6rn_Lindqvist?= | last post by:
With regexps you can search for strings matching it. For example, given the regexp: "foobar\d\d\d". "foobar123" would match. I want to do the reverse, from a regexp generate all strings that could match it. The regexp: "{3}\d{3}" should generate the strings "AAA000", "AAA001", "AAA002" ... "AAB000", "AAB001" ... "ZZZ999". Is this possible to do? Obviously, for some regexps the set of matches is unbounded (a list of everything that...
27
3249
by: SQL Learner | last post by:
Hi all, I have an Access db with two large tables - 3,100,000 (tblA) and 7,000 (tblB) records. I created a select query using Inner Join by partial matching two fields (X from tblA and Y from tblB). The size of the db is about 200MBs. Now my issue is, the query has been running for over 3 hours already - I have no idea when it will end. I am using Access 2003. Are there ways to improve the speed performance? (Also, would the...
5
1074
by: Johny | last post by:
I have the following text <title>Goods Item 146 (174459989) - OurWebSite</title> from which I need to extract `Goods Item 146 ' Can anyone help with regexp? Thank you for help L.
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10437
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9042
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3723
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.