a coder
a coder

Reputation: 7659

Using RegEx to extract number from alphanumeric string

I need to identify substring 'X.123' and/or 'X.8' in a longer string of alphanumeric data. Ex:

A cow flew over the moon in the X.123 module, not the X.124.3 module, 
and certainly not the X.125C78 module.  The cow poo-pooed the X.8 module.

How would I exclude the second and third instance? This is what I've come up with so far to get the "X.123" part:

/[X][\.][0-9]{1,4}/

I'm not exactly sure how to make the expression stop at any non-numeric character (ex: X124C78)

Help greatly appreciated!

Upvotes: 4

Views: 1930

Answers (3)

FailedDev
FailedDev

Reputation: 26940

I would use this. The \b in the start helps avoiding matches such as AX.123

/\bX\.\d+(?=\s|$)/

preg_match_all('/\bX\.\d+(?=\s|$)/', $subject, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
    # Matched text = $result[0][$i];
}

Upvotes: 1

rand0m
rand0m

Reputation: 56

The \b is nice in this context, i would use it like this:

/\bX\.\d{1,4}\b/

Upvotes: 4

Regexident
Regexident

Reputation: 29562

Try this:

/X\.[0-9]{1,4}(?=\s|$)/

Upvotes: 2

Related Questions