473,837 Members | 1,476 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 2227
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
5496
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
2372
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
39366
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
1836
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
2036
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
1914
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
6907
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
3252
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
1076
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
9682
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
10566
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10272
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7806
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7001
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
5669
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
5848
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4474
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
4040
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.