PDA

View Full Version : Regex Number followed by symbol issue

mathceleb
11-04-2010, 07:55 PM
Why is the 3rd term not -6_?

\$lefteq="-x+2+10x-9-6_";
\$lct = preg_match_all('/(\-)?(\d+)(\-|\+|\=|\>|\<|\_)/', \$lefteq, \$match, PREG_PATTERN_ORDER);
for (\$x=0;\$x<\$lct;\$x++){
\$curvalue=\$match[0][\$x];
echo "curvalue = " . \$curvalue . "<br />";
\$curvalue=substr(\$curvalue,0,strlen(\$curvalue)-1);
array_push(\$lconst,\$curvalue);
}
which produces

curvalue = 2+
curvalue = -9-
curvalue = 6_

MattF
11-04-2010, 08:02 PM
\$lct = preg_match_all('/(\-)?(\d+?)(\-|\+|\=|\>|\<|\_)/', \$lefteq, \$match, PREG_PATTERN_ORDER);

or:

\$lct = preg_match_all('/(\-)?(\d+)(\-|\+|\=|\>|\<|\_)/u', \$lefteq, \$match, PREG_PATTERN_ORDER);

or:

\$lct = preg_match_all('/^(\-)?(\d+)(\-|\+|\=|\>|\<|\_)/', \$lefteq, \$match, PREG_PATTERN_ORDER);

should do as you expect.

mathceleb
11-04-2010, 08:28 PM
2 of them did the same as what I had, and the one with the line starter ^ showed nothing.

MattF
11-04-2010, 09:29 PM
What is it supposed to match? All or part of the string? If partial, which part? Btw, do a search on Google or such for 'PCRE cheat sheet'. It'll help with the specifics of regex.

mathceleb
11-04-2010, 09:55 PM
It is supposed to match any number, positive or negative, followed by an operator sign or an underscore.

The only trouble I have in unit testing is that a negative number followed by a negative number comes up as negative positive. Everything else works like a charm.

I'll check the cheatsheet out.

mathceleb
11-04-2010, 10:04 PM
Tried this instead, I removed the underscore from the end of \$lefteq:
I'm looking for any number not followed by a letter. This gives the last negative number, but also gives the 1 in the number 10.

\$lct = preg_match_all('/(\-?)(\d+)(?![a-z])/', \$lefteq, \$match, PREG_PATTERN_ORDER);

mathceleb
11-04-2010, 10:10 PM
Fixed. I needed boundaries on the number. This solves my problem:

\$lct = preg_match_all('/(\-?)\b(\d+)\b(?![a-z])/', \$lefteq, \$match, PREG_PATTERN_ORDER);

MattF
11-04-2010, 10:19 PM
I'm looking for any number not followed by a letter.

I'm a bit rusty, but try this:

preg_match_all('/(\d+)(?![a-z])/', \$lefteq, \$match, PREG_PATTERN_ORDER);

Try looking in \$match[1] instead of \$match[0] too.

Edit: You shouldn't need to use the boundary marker.