473,626 Members | 3,245 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using C# Regex.IsMatch to validate 4 digit string?

All I am trying to do is use Regex.IsMatch to validate that a string is
either empty, or exactly 4 characters (digits) in length. In other words,
the strings, "", and "1234" should pass, whereas "123", "abcd", and "12345"
should fail. I know there has to be a simple answer to this, but right now
I can't find it. I tried using:

if (str.Length == 0)

return true;

if (Regex.IsMatch( str, "[0-9]^4"))

return true;

but this does not work. Variations such as

Regex.IsMatch(" 1234", @"\d\d\d\d") come close, but also result in "12345"
validating.

Any help would be greatly appreciated.


Nov 15 '05 #1
2 28708
Hi Byron,

You have to use ^ and $ to indicate start and end of the string:
Regex.IsMatch(" 1234", @"^\d\d\d\d$ ")

should do the trick.

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Byron" <si*****@ctcorp .com> wrote in message
news:e0******** ******@TK2MSFTN GP10.phx.gbl...
All I am trying to do is use Regex.IsMatch to validate that a string is
either empty, or exactly 4 characters (digits) in length. In other words,
the strings, "", and "1234" should pass, whereas "123", "abcd", and "12345" should fail. I know there has to be a simple answer to this, but right now I can't find it. I tried using:

if (str.Length == 0)

return true;

if (Regex.IsMatch( str, "[0-9]^4"))

return true;

but this does not work. Variations such as

Regex.IsMatch(" 1234", @"\d\d\d\d") come close, but also result in "12345"
validating.

Any help would be greatly appreciated.

Nov 15 '05 #2
That did the trick. Thanks for the quick reply
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
in message news:OF******** *****@TK2MSFTNG P12.phx.gbl...
Hi Byron,

You have to use ^ and $ to indicate start and end of the string:
Regex.IsMatch(" 1234", @"^\d\d\d\d$ ")

should do the trick.

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Byron" <si*****@ctcorp .com> wrote in message
news:e0******** ******@TK2MSFTN GP10.phx.gbl...
All I am trying to do is use Regex.IsMatch to validate that a string is
either empty, or exactly 4 characters (digits) in length. In other words, the strings, "", and "1234" should pass, whereas "123", "abcd", and

"12345"
should fail. I know there has to be a simple answer to this, but right

now
I can't find it. I tried using:

if (str.Length == 0)

return true;

if (Regex.IsMatch( str, "[0-9]^4"))

return true;

but this does not work. Variations such as

Regex.IsMatch(" 1234", @"\d\d\d\d") come close, but also result in "12345" validating.

Any help would be greatly appreciated.


Nov 15 '05 #3

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

Similar topics

5
2316
by: Henry | last post by:
I have this simple code, string escaped = Regex.Escape( @"`~!@#$%^&*()_=+{}\|;:',<.>/?" + "\"" ); string input = @"a&+" + "\"" + @"@(-d)\e"; Regex re = new Regex( string.Format(@"(+)", escaped), RegexOptions.CultureInvariant ); string s = re.Replace( input, "" ); It doesn't seem to work, regular expression return without filter out any character
1
1720
by: Colin Reid | last post by:
Hey MS, here's an apparent problem in the base class library. I pulled the email validation pattern "^((*)*@(()+(*)*\.)+{2,9})" from http://regexlib.com. If I validate the email address "test@someverylongemailaddress.com" against it by just creating a RegEx and calling IsMatch it works fine, but if I create a schema defining a simple type restricting an xs:string by the regex pattern, it takes over full minute at 100% cpu to match....
2
6628
by: Doug | last post by:
I'm a little confused by this functionality. It doesn't seem to be behaving like it should. I am using the following regular expression to validate email addresses: "\w+(\w+)*@\w+(\w+)*\.({2,4})\040*". From what I can determine it should validate the following rules: 1. BEFORE THE AMPERSAND A. Must contain at least one alphanumeric character.
2
8102
by: live your lives | last post by:
i am trying to validate a simple username textbox using RegularExpressionValidator: TextBox tbUserName = new TextBox(); tbUserName.ID = "tbUserName"; string strPatternUserName = @"\W"; // i've tried using "\\W", "\w", "\\w","@\w", "/\\w", etc... // but it always prints my error msg UNLESS the textbox is set to "". // why does this not work?
4
2851
by: Jon Maz | last post by:
Hi All, Am getting frustrated trying to port the following (pretty simple) function to CSharp. The problem is that I'm lousy at Regular Expressions.... //from http://support.microsoft.com/default.aspx?scid=kb;EN-US;246800 function fxnParseIt() { var sInputString = 'asp and database';
5
2263
by: Dennis | last post by:
Should not the following return False if s="255xxxxyyy"? It seems to return True. Regex.IsMatch(s, "") -- Dennis in Houston
4
2793
by: ad | last post by:
I am useing VS2005 to develop wep application. I use a RegularExpress both in RegularExpressionValidator and Regex class to validate a value. The RegularExpress is 20|\-9|\-1|?\d{1} When I enter 33 and validate with RegularExpressionValidator, it fail to pass. But when I validate with regex class : Regex.IsMatch(Sight0L, @"20|\-9|\-1|?\d{1}");
0
1538
by: Tidane | last post by:
Visual Basic.NET Framework 2.0 I've created a program to parse out text as the program recieved it and use Regex matching to decide what should be done. My problem is that the text is matching when it shouldn't be, if that makes any sense. If Regex.IsMatch(Text, "You find (a|an)" & MoneyMatch) Then Other code here that doesn't matter. ElseIf Regex.IsMatch(Text, "(+\s)obtains (a|an)") Then More code that doesn't matter. EndIf
7
2226
by: =?Utf-8?B?amFj?= | last post by:
Hi, I have problems with following code and don’t find the bug : // Set ArrayList aArray = new ArrayList(); regStr = new Regex(@"\?)*(\d+)\]"); if(text != null && regStr.IsMatch(text)) {
0
8269
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
8711
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
7203
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...
1
6125
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
5576
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
4094
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
4206
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1515
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.