Jump to content

so lost on simply regex expression


M.O.S. Studios

Recommended Posts

i using regex in a simple function.

 

bascily i need to know if the value fits the following 2 criteria.

 

1. the first character is a + or -

2. the rest of the string is nothing but digits (only numbers, no decimals or other punctuation).

 

 

this is what i tried

 


([+-]{1})([0-9])

 

the problem is it only checks the frst two characters, so this would pass '+1helloworld'.

 

can any one help?

Link to comment
Share on other sites

didn't work, but this did.

^([-+]|\d)((?![^0-9])[0-9])+$

 

for those of who found this while trying to do something similar I'll explain why.

 

^means see if the first fist this [-+]|\d. (brackets are added to mark what is included in the ^ command).

[-+]|\d means the assigned search has to be + - or  a number.

then there is this.

((?![^0-9])[0-9])+$

(?![^0-9])[0-9]) means make sure there is no characters that are not between the numbers between 0 and 9.

then +$ means start from the end and check until it is false.

 

 

i hope this is clear. and if anyone see that i didn't explain it properly let me know!

Link to comment
Share on other sites

My mistake, just forgot to escape the plus. Although can make it simpler, as you kind of did, by using block brackets for matching the plus/minus:

 

var_dump(preg_match('/^[-+]?[0-9]+$/', '-123456')); // returns 1

The pattern you came up with though is just making it more complicated than it needs to be.

Link to comment
Share on other sites

A simple alternative would be /^[-+]?\d+$/D  which would match: one or more decimal digits optionally preceded by either a plus or a minus character.  The D pattern modifier is used to disallow a newline (e.g. "12345\n") which the other suggested ones would allow.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.