473,592 Members | 2,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I do this without Regex ?


Is there a way to write a faster function ?

public static bool IsNumber( char Value )
{
if (Regex.IsMatch( Value.ToString( ), @"^[0-9]+$" ))
{
return true;
}
else return false;
}

I think, if I have to repat this some thousands time, it
could become very time consuming.

Thanks in advance,

P.S.
Is there in C# something similar to Delphi's sets ?

Nov 15 '05 #1
9 4568
Tim Conner <Ti*******@disc ussions.microso ft.com> wrote:
Is there a way to write a faster function ?

public static bool IsNumber( char Value )
{
if (Regex.IsMatch( Value.ToString( ), @"^[0-9]+$" ))
{
return true;
}
else return false;
}

I think, if I have to repat this some thousands time, it
could become very time consuming.


While regular expressions are very powerful, they're not very fast for
doing simple thing - and you're creating a new string for each call as
well. Far simpler and faster is:

public static bool IsNumber (char value)
{
return (value>='0' && value <='9');
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Why don't you try the framework given method ?
Check the Char.IsNumber( ) ?

For example :
Console.WriteLi ne(Char.IsNumbe r('8')); // Output: "True"

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Tim Conner <Ti*******@disc ussions.microso ft.com> wrote:
Is there a way to write a faster function ?

public static bool IsNumber( char Value )
{
if (Regex.IsMatch( Value.ToString( ), @"^[0-9]+$" ))
{
return true;
}
else return false;
}

I think, if I have to repat this some thousands time, it
could become very time consuming.


While regular expressions are very powerful, they're not very fast for
doing simple thing - and you're creating a new string for each call as
well. Far simpler and faster is:

public static bool IsNumber (char value)
{
return (value>='0' && value <='9');
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #3
Tim,
In addition to Jon's comments.

Is there a reason you are not using the static Char.IsDigit or Char.IsNumber
function?
public static bool IsNumber( char Value )
{ return Char.IsDigit(Va lue); }
Char has a number of other static functions that check the character's
class.

FWIW, when I have a static method that is checking a 'constant' regex, I
normally create a static Regex field, then use that. This way the regex
object itself is not continueally recreated. I even consider making this
Regex compiled with the RegexOptions.Co mpiled option, to get even a little
more performance out of it. Seeing as its static, there is only going to be
one anyway.

Something like:

static readonly Regex thePattern = new Regex(@"^[0-9]+$",
RegexOptions.Co mpiled);
public static bool IsNumber( string value )
{ return thePattern.IsMa tch(value); }
Hope this helps
Jay
"Tim Conner" <Ti*******@disc ussions.microso ft.com> wrote in message
news:08******** *************** *****@phx.gbl.. .
Is there a way to write a faster function ?

public static bool IsNumber( char Value )
{
if (Regex.IsMatch( Value.ToString( ), @"^[0-9]+$" ))
{
return true;
}
else return false;
}

I think, if I have to repat this some thousands time, it
could become very time consuming.

Thanks in advance,

P.S.
Is there in C# something similar to Delphi's sets ?

Nov 15 '05 #4

I have another similar routines, for check alpha numeric,
and to test for integers and floats. So, I did that just
by inertia <g>. I may change this routine since it is very
straight forward, numbers are numbers, so no more to check
here.

But for my other routines, I think I do need regex. For
example the following :

public static bool IsFloat( string Value)
{
if (Regex.IsMatch( Value.ToString( ), @"^[+-]?([0-9]*\.?
[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$" ))
{
return true;
}
else return false;

}
I am using the static IsMatch of Regex. So I think I am
not recreating a regex object each time.
But your code seems slightly different.
But I am not sure about "that" difference <g>.
Would you mind to explain a bit more on this ?
Thanks in advance,


-----Original Message-----
Tim,
In addition to Jon's comments.

Is there a reason you are not using the static Char.IsDigit or Char.IsNumberfunction?
public static bool IsNumber( char Value )
{ return Char.IsDigit(Va lue);
}


Char has a number of other static functions that check

the character'sclass.

FWIW, when I have a static method that is checking a 'constant' regex, Inormally create a static Regex field, then use that. This way the regexobject itself is not continueally recreated. I even consider making thisRegex compiled with the RegexOptions.Co mpiled option, to get even a littlemore performance out of it. Seeing as its static, there is only going to beone anyway.

Something like:

static readonly Regex thePattern = new Regex(@"^[0-9] +$",RegexOptions.C ompiled);
public static bool IsNumber( string value )
{ return thePattern.IsMa tch(value);
}


Hope this helps
Jay
"Tim Conner" <Ti*******@disc ussions.microso ft.com> wrote

in messagenews:08******* *************** ******@phx.gbl. ..

Is there a way to write a faster function ?

public static bool IsNumber( char Value )
{
if (Regex.IsMatch( Value.ToString( ), @"^[0-9] +$" )) {
return true;
}
else return false;
}

I think, if I have to repat this some thousands time, it
could become very time consuming.

Thanks in advance,

P.S.
Is there in C# something similar to Delphi's sets ?

.

Nov 15 '05 #5
Tim,
I am using the static IsMatch of Regex. So I think I am
not recreating a regex object each time. Correct you are not explicitly creating a regex object each time, however
the static method IS implicitly creating a regex object each time for you.
Read the description of the static IsMatch carefully!

http://msdn.microsoft.com/library/de...atchTopic3.asp

The Remarks state: "The two static IsMatch methods are equivalent to
constructing a Regex object with the specified regular expression pattern
and calling the instance method IsMatch. The static methods are provided to
allow an isolated, single use of a regular expression without explicitly
creating a Regex object."

Note "isolated, single use" and "equivalent to constructing a regex object"
in the above statement. I would expect your IsFloat method to be called a
number of different times from a number of different places...
But your code seems slightly different.
But I am not sure about "that" difference <g>.
Would you mind to explain a bit more on this ? What do you mean different? Do you mean I simply return the bool value,
rather then checking for true and returning true?

you effectively have:

bool rc = Regex.IsMath(.. .)

if (rc)
return true
else
return false;

where as I effectively have:

bool rc = Regex.IsMath(.. .)

return rc;

I used an explaining variable in the above sample, however they are the
same.

Or that you were passing a char, I modified it to pass a string.

Or that I created an object, and use an instance method of the object?

In your IsFloat routine, I would simply use:

private static readonly Regex floatPattern = new
Regex(@"^[+-]?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$",
RegexOptions.Co mpiled);

public static bool IsFloat(string value)
{
return floatPattern.Is Match(value)
}

floatPattern is:
- private : as its an implementation detail
- static : as we only need one instance of it
- readonly : as we don't need to change it after its initialized

IsFloat uses the above Regex to check for a match, value is already a
string, so we do not need to call ToString a second time. Seeing as
Regex.IsMatch returns a bool, we can simply return this bool. IsFloat
encapsulates the Regex object.

Hope this helps
Jay

"Tim Conner" <Ti*******@disc ussions.microso ft.com> wrote in message
news:09******** *************** *****@phx.gbl.. .
I have another similar routines, for check alpha numeric,
and to test for integers and floats. So, I did that just
by inertia <g>. I may change this routine since it is very
straight forward, numbers are numbers, so no more to check
here.

But for my other routines, I think I do need regex. For
example the following :

public static bool IsFloat( string Value)
{
if (Regex.IsMatch( Value.ToString( ), @"^[+-]?([0-9]*\.?
[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$" ))
{
return true;
}
else return false;

}
I am using the static IsMatch of Regex. So I think I am
not recreating a regex object each time.
But your code seems slightly different.
But I am not sure about "that" difference <g>.
Would you mind to explain a bit more on this ?
Thanks in advance,


-----Original Message-----
Tim,
In addition to Jon's comments.

Is there a reason you are not using the static

Char.IsDigit or Char.IsNumber
function?
public static bool IsNumber( char Value )
{

return Char.IsDigit(Va lue);
}


Char has a number of other static functions that check

the character's
class.

FWIW, when I have a static method that is checking

a 'constant' regex, I
normally create a static Regex field, then use that. This

way the regex
object itself is not continueally recreated. I even

consider making this
Regex compiled with the RegexOptions.Co mpiled option, to

get even a little
more performance out of it. Seeing as its static, there

is only going to be
one anyway.

Something like:

static readonly Regex thePattern = new Regex(@"^[0-9]

+$",
RegexOptions.C ompiled);
public static bool IsNumber( string value )
{

return thePattern.IsMa tch(value);
}


Hope this helps
Jay
"Tim Conner" <Ti*******@disc ussions.microso ft.com> wrote

in message
news:08******* *************** ******@phx.gbl. ..

Is there a way to write a faster function ?

public static bool IsNumber( char Value )
{
if (Regex.IsMatch( Value.ToString( ), @"^[0-9] +$" )) {
return true;
}
else return false;
}

I think, if I have to repat this some thousands time, it
could become very time consuming.

Thanks in advance,

P.S.
Is there in C# something similar to Delphi's sets ?

.

Nov 15 '05 #6
> I have another similar routines, for check alpha numeric,
and to test for integers and floats. So, I did that just
by inertia <g>. I may change this routine since it is very
straight forward, numbers are numbers, so no more to check
here.

Don't validate to much.
Some day the marketing team will decide they can sell
this in Europe and you have to translate it.
And suddenly you validations go down the drain.
Your alpha numeric will not accept accented characters,
your float will not accept numbers where the
decimal point is comma, etc.

Mihai
Nov 15 '05 #7
Bsiang Tan <tb*********@ho tmail.com> wrote:
Why don't you try the framework given method ?
Check the Char.IsNumber( ) ?

For example :
Console.WriteLi ne(Char.IsNumbe r('8')); // Output: "True"


Actually, what was asked for is really Char.IsDigit (ie just 0-9) - but
I wouldn't have spotted that if you hadn't raised it :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8
The simplest would be to do a float.Parse(myS tring) and check wheather a
exception occures or not.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Nov 15 '05 #9
codymanix <do************ *********@gmx.d e> wrote:
The simplest would be to do a float.Parse(myS tring) and check wheather a
exception occures or not.


And the fastest would be to do some preliminary validation before
calling float.Parse. Again, writing a small routine which knows about
floating point formats is likely to be fairly simple, and significantly
faster than a regex.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #10

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

Similar topics

2
1767
by: actarus | last post by:
I need a Regex that find just a text inside a string that has both text and tags html, for example : string str = "<table ....><tr><td>my table</td></tr></table> I want a Regex that return just my table. Could someone help me? Thanks.
3
2333
by: Craig Kenisston | last post by:
I have the sudden need to split a text that may have any of the following tokens : Words with quotes or double quotes. Words with no quotes at all. Numbers with and without decimal points, no commas allowed, but may contain parenthesis which I would like to keep apart to drop later. They may be separated by comas, spaces or semicolon.
6
2491
by: Extremest | last post by:
I have a huge regex setup going on. If I don't do each one by itself instead of all in one it won't work for. Also would like to know if there is a faster way tried to use string.replace with all the right parts in there in one big line and for some reason that did not work either. Here is my regex's. static Regex rar = new Regex("\\.part.*", RegexOptions.IgnoreCase); static Regex par = new Regex("\\.vol.*", RegexOptions.IgnoreCase);
7
2576
by: Extremest | last post by:
I am using this regex. static Regex paranthesis = new Regex("(\\d*/\\d*)", RegexOptions.IgnoreCase); it should find everything between parenthesis that have some numbers onyl then a forward slash then some numbers. For some reason I am not getting that. It won't work at all in 2.0
4
3137
by: Peter | last post by:
Hi all, I am searching through directories trying to find the prefix to a number of files. Unfortunately the files don't have a standard naming convention yet. So some of them appear as: THH307A.Monitoring Public Health Issues.doc ' A single period THH307A- Monitoring Public Health Issues.doc ' A hyphen, space THH307A Monitoring Public Health Issues.doc ' A single space
16
2243
by: Mark Chambers | last post by:
Hi there, I'm seeking opinions on the use of regular expression searching. Is there general consensus on whether it's now a best practice to rely on this rather than rolling your own (string) pattern search functions. Where performance is an issue you can alway write your own specialized routine of course. However, for the occasional pattern search where performance isn't an issue, would most seasoned .NET developers rely on "Regex" and...
8
2772
by: Diwa | last post by:
Hi Guys, Is there any better way than below to find an int in a string (e.g. "30" in "KFStat30A") // -------------------------------------------------------------- #include <iostream> #include <sstream> #include <vector>
4
1834
by: wildman | last post by:
RE: Replacing Text without changing case?? This code works great, but case has to be exact. Research.Text = Research.Text.Replace(textboxSearch.Text, "<b>" + textboxSearch.Text + "</b>") I found some c# code, but I can't make it work in vb.net:
7
1671
by: Vipul03 | last post by:
I want to search a regex in perl without replacing it and without going line by line to search it Any help will be apriciable Thanks in advance
0
7935
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
7871
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,...
1
7995
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8227
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...
0
5400
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
3851
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...
1
2379
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
1
1467
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1202
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.