I need get "v3.4.2" in string by regex php. String: "ABCDEF v3.4.2 GHI KLMN";
            Asked
            
        
        
            Active
            
        
            Viewed 57 times
        
    -6
            
            
        - 
                    1it is fixed value or variant – Santosh Ram Kunjir Apr 07 '16 at 08:42
- 
                    it is variant @SantoshRamKunjir – user3912569 Apr 07 '16 at 08:43
- 
                    starts with v and length is fixed? – Santosh Ram Kunjir Apr 07 '16 at 08:44
- 
                    length is variant. example: v1.0, v1.3.2.3, v3.4.3.2.3 – user3912569 Apr 07 '16 at 08:46
- 
                    @user3912569 A fairly easy task. What have you tried and how did it fail? – Biffen Apr 07 '16 at 08:47
1 Answers
1
            
            
        A safe RegEx to work with variable lengths and digits:
\bv(\d+\.)+\d+\b
How it works:
\b          # Word Boundary
v           # v
(\d+\.)     # Digit(s) followed by . - i.e. 3. or 4.
+           # Match many digit(s) followed by dot - i.e. 3.4.2. or 5.6.
\d+         # Final digit of version (not included above because it has no trailing .)
\b          # Word Boundary
If the format is exactly as shown, use this shorter RegEx:
\bv\d\.\d\.\d\b
\b marks a word boundary, so it will not capture inside donotv3.4.2capturethis
How it works:
\b             # Word Boundary
v              # v
\d\.\d\.\d     # 3.4.2
\b             # Word Boundary
 
    
    
        Kaspar Lee
        
- 5,446
- 4
- 31
- 54
- 
                    First of all it's not matching variable length. Second it will leave trialing dot and will match everything else in `v3.4.2.` – Apr 07 '16 at 09:05
- 
                    1@noob Fair point. But that trailing dot could be a full stop, e.g. `We released a new version of our product, v3.4.2. It is very good and has .....`. And how does it not match a variable length? It will match `v33.44.22` and `v3.4.2.3.4.2`? – Kaspar Lee Apr 07 '16 at 09:08
- 
                    [This is how it's not matching variable length.](https://regex101.com/r/kR4bW3/2) P.S: I see this was your initial regex. You seem to have edited you answer 18 minutes ago. – Apr 07 '16 at 09:10
- 
                    @noob **You used the wrong RegEx!** Use the top one, the one I explicitly stated as to match variable length! [**New Demo**](https://regex101.com/r/kR4bW3/3) – Kaspar Lee Apr 07 '16 at 09:12
- 
                    @Biffen: I did read the initial one which was wrong. And also the **Edited one 20 minutes ago**. – Apr 07 '16 at 09:13
- 
                    1@noob You wrote your comment about it not match variable length 8 mins ago. This is 13 mins **after** I edited it – Kaspar Lee Apr 07 '16 at 09:14
- 
                    
- 
                    
