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
https://forums.phpfreaks.com/topic/215534-so-lost-on-simply-regex-expression/
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!

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.