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
You could use the below regex to match the version number.
\b\d+(?:\.\d+)*\b
\bword 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'