Using RegEx to extract a number from an alphanumeric string

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

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 can I exclude the second and third instance? This is what I came to get the "X.123" part:

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

I'm not quite sure how to make an expression dwell on any non-numeric character (ex: X124C78)

Help with thanks!

+4
source share
3 answers

\ b is good in this context, I would use it like this:

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

Try the following:

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

I would use this. \b at the beginning helps to avoid matches like 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]; } 
+1
source

Source: https://habr.com/ru/post/1380942/


All Articles