I have a CSS (or HTML or JS) file with a comment /* Version: 1.2.1 */
near the beginning of the file.
Using PHP/regex, how do I get a string containing '1.2.1'
?
I apologise for not RTFM but I can't find an answer on the Google. Any direction on learning regex would be great!
$str = '/* Version 1.2.1 */';
preg_match('/version\s(.*)\s\*/i',$str,$matches);
print_r($matches[1]);
its very simple to grap,
\s(.*)\s
capture anything in betweenspaces
as first group. display first captured group$matches[1]
if you are curious that how it works or wanna learn yourself ? you can dive directly into it from here i found this very helpful for beginner.
To begin with regex learning, I strongly recommend these two sites:
To test your regex regex101 is particularly usefull.
That being said, you have two options to consider:
If you can work with a capture group, simple regex will work:
^\s*\/\* Version: (\d\.\d\.\d) \*\/
This will capture the version number in group 1 (demo).
When you want to only get the matching version number but don't want to bother with a capture group, you have to work with lookarounds:
(?<=\/\* Version: )
.(?= \/\*)
.Assembled with version number matching (demo):
(?<=\/\* Version: )\d\.\d\.\d(?= \*\/)