1

What I want is simple. I will use JavaScript or PHP to get a file from a source. When I get the file's name, it will have a format like source-file-1.0.0-stable.zip. After some time, the file could become source-file-1.2.0-stable.zip. I want to extract the version from this file name. Can it be done with regex? Is there any PHP function that would be able to do that only with the string and the regex? I don't want to use other functions, like explode(), strpos() or whatever elese

1 Answer 1

5

You could use the below regex to match the version number.

\b\d+(?:\.\d+)*\b
  • \b word boundary which matches between a word character and a non-word character.

  • \d+ Matches one or more digits.

  • (?:...) Called non-capturing group. (?:\.\d+) Matches a dot and the following one or more digits. (?:\.\d+)* , matches a dot and the following one or more digits zero or more times. * repeats the previous token zero or more times. If the version number must contain a dot, then change the * in this pattern (?:\.\d+)* to +. + repeats the previous token one or more times.

In js, it would be like

> "source-file-1.0.0-stable.zip".match(/\b\d+(?:\.\d+)*\b/)[0]
'1.0.0'
Sign up to request clarification or add additional context in comments.

2 Comments

Very good @avinash Raj. Indra Use above regex code as : preg_match('/\b\d+(?:\.\d+)*\b/',$sourcestring,$matches); $matches[0] is your answer.
Great answer. Thanks for the explanation, too. I really needed that, as I am a beginner in the world of regular expressions. For those interested, in PHP you use preg_match

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.