We help IT Professionals succeed at work.

Need a regular expression in c#

Star79
Star79 used Ask the Experts™
on
Hello,

I need a regular expression in c# which accepts + only in the begining. Currently i am using this
[-+]?[0-9]*  but this will allow special character + to be inserted anywhere in the string.

Regards,
Rithesh
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
kaufmedGlanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
You simply need to add the beginning-of-string marker:
^[-+]?[0-9]*

Open in new window

Commented:
I think what you really need is

^[-+]?[0-9]+

Open in new window

kaufmedGlanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Actually, you might need to add a bit more to the pattern. The above would still allow the following:

    +123+
    +123ABC

etc. Let's add the end-of-line-marker as well:

^[-+]?[0-9]*$

Open in new window


Change the * to a + if you require at least one digit, as pmasotta demonstrates.

Commented:
the former one also match single + or - signs

+
-

this one requires a valid integer number per line

^[-+]?[0-9]*$

Open in new window

Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
this one requires a valid integer number per line
No it doesn't. You forgot to change the star to a plus as I noted in the post above yours   ; )
Commented:
you are right hahahahah

but at the end you didn't write the good one that it is this one ;-)

^[-+]?[0-9]+$ 

Open in new window