-6

I need get "v3.4.2" in string by regex php. String: "ABCDEF v3.4.2 GHI KLMN";

1 Answers1

1

A safe RegEx to work with variable lengths and digits:

\bv(\d+\.)+\d+\b

Live Demo on Regex101

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

Live Demo on Regex101

\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
  • Good luck with upvotes and points. Am out of here. –  Apr 07 '16 at 09:15
  • `:D` Thanks, see you later! – Kaspar Lee Apr 07 '16 at 09:18