Dynadot โ€” .com Registration $8.99

Regular Expression Question

Spaceship Spaceship
Watch

evdoxos

Established Member
Impact
0
The following regular expression matches floating point numbers:

Code:
"/([-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?)/"
Could someone tell me what is the purpose of ?:
I mean what problem could take place if I omit this.
 
Last edited:
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
AfternicAfternic
0
•••
I can't find an expression that the following two patterns have different output. Can you?

Code:
"/(?:[0-9]+[a-z]+)*/"
Code:
"/([0-9]+[a-z]+)*/"
 
0
•••
both of the patterns match so no the output will generally be the same however with the 1 that has the ?: in it, the pattern that is after the ?: will not be a part of the returned results.

Take the following example:-

PHP:
<?php
preg_match("/(?:[a-z]+)([123]+)*/", 'test123', $matches);
print_r($matches);

preg_match("/([a-z]+)([123]+)*/", 'test123', $matches2);
print_r($matches2);
?>

the output put is :-

PHP:
Array
(
    [0] => test123
    [1] => 123
)
Array
(
    [0] => test123
    [1] => test
    [2] => 123
)

as you can see test is not a part of the output in the 1st array. This is because the pattern that matched it was preceeded by the ?: (the 0 index is always the pull string that matched the whole pattern).

Some characters such as the ? have multiple meanings the ? can also be used to make something optional for example:-

"/([a-z])([0-9])?/"

That reg exp would quite happy return results for a, a1, b, b1 etc etc. The reason for it matching single letters as well is because the part of the regular expression that matches the number is optional.

"/([a-z])([0-9])/"

that on the other hand would only ever match a letter followed by a number as it is no longer optional.
 
0
•••
At the first pattern which matches floating point numbers
(eg: 1.2e+3 , .2e-3 , 1e3 , 1.2 , .2 , 1 )

Code:
"/([-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?)/"
In this pattern are ?: useful or not?
Do you see any number could not match the pattern if we remove all of them?
 
0
•••
no removing the ?: will not make any difference unless you use the subpatterns for something else
 
0
•••
Thank you.
 
0
•••
Appraise.net
Unstoppable Domains
Domain Recover
DomainEasy โ€” Zero Commission
  • The sidebar remains visible by scrolling at a speed relative to the pageโ€™s height.
Back